redux toolkit auth code example

Example 1: redux toolkit

import { createSlice } from '@reduxjs/toolkit';

export const counterSlice = createSlice({
  name: 'counter',
  initialState: {
    value: 0,
  },
  reducers: {
    increment: state => { 
      state.value += 1;
    },
    decrement: state => {
      state.value -= 1;
    },
    incrementByAmount: (state, action) => {
      state.value += action.payload;
    },
  },
});

export const { increment, decrement, incrementByAmount } = counterSlice.actions;

export const selectCount = state => state.counter.value;

export default counterSlice.reducer;

Example 2: 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);