auth with redux toolkit code example
Example: authentication with redux toolkit
1export const loginUser = createAsyncThunk(2 'users/login',3 async ({ email, password }, thunkAPI) => {4 try {5 const response = await fetch(6 'https://mock-user-auth-server.herokuapp.com/api/v1/auth',7 {8 method: 'POST',9 headers: {10 Accept: 'application/json',11 'Content-Type': 'application/json',12 },13 body: JSON.stringify({14 email,15 password,16 }),17 }18 );19 let data = await response.json();20 console.log('response', data);21 if (response.status === 200) {22 localStorage.setItem('token', data.token);23 return data;24 } else {25 return thunkAPI.rejectWithValue(data);26 }27 } catch (e) {28 console.log('Error', e.response.data);29 thunkAPI.rejectWithValue(e.response.data);30 }31 }32);