JonJon
JonJon

Reputation: 179

Migrating from Redux to Redux toolkit

I'm slowly migrating over from Redux to Redux toolkit. I'm still pretty new but I have this login action function. How can I translate old function below do I need createAsyncThunk to achieve this?

export const login = (email, password) => (dispatch) => {
  dispatch(requestLogin());
  firebase
    .auth()
    .signInWithEmailAndPassword(email, password)
    .then((user) => {
      dispatch(responseLogin(user));
    })
    .catch((error) => {
      dispatch(loginError());
    });
};

and my auth slice looks something like this:

const authSlice = createSlice({
  name: "authSlice",
  initialState: {
    isLoggingIn: false,
    isLoggingOut: false,
    isVerifying: false,
    loginError: false,
    logoutError: false,
    isAuthenticated: false,
    user: {},
  },
  reducers: {
    signInWithEmail: (state, action) => {
      const { email, password } = action.payload;
      firebase
        .auth()
        .signInWithEmailAndPassword(email, password)
        .then((response) => {
          const {
            uid,
            email,
            emailVerified,
            phoneNumber,
            password,
            displayName,
            photoURL,
          } = response.user;
        })
        .catch((error) => {
          console.log(error);
        });
    },
  },
  extraReducers: {},
});

Upvotes: 1

Views: 1888

Answers (2)

SHUVO MUSA
SHUVO MUSA

Reputation: 554

Lets create a productSlice.js

import { createSlice,createSelector,PayloadAction,createAsyncThunk,} from "@reduxjs/toolkit";

export const fetchProducts = createAsyncThunk(
  "products/fetchProducts", async (_, thunkAPI) => {
     try {
        const response = await fetch(`url`); //where you want to fetch data
        return await response.json();
      } catch (error) {
         return thunkAPI.rejectWithValue({ error: error.message });
      }
});

const productsSlice = createSlice({
   name: "products",
   initialState: {
      products: [],
      loading: "idle",
      error: "",
   },
   reducers: {},
   extraReducers: (builder) => {
      builder.addCase(fetchProducts.pending, (state) => {
        state. products = [];
          state.loading = "loading";
      });
      builder.addCase(
         fetchProducts.fulfilled, (state, { payload }) => {
            state. products = payload;
            state.loading = "loaded";
      });
      builder.addCase(
        fetchProducts.rejected,(state, action) => {
            state.loading = "error";
            state.error = action.error.message;
      });
   }
});


export const selectProducts = createSelector(
  (state) => ({
     products: state.products,
     loading: state.products.loading,
  }), (state) =>  state
);
export default productsSlice;

In your store.js add productsSlice: productsSlice.reducer in out store reducer.

Then for using in component add those code ... I'm also prefer to use hook

import { useSelector, useDispatch } from "react-redux";

import { fetchProducts,selectProducts,} from "path/productSlice.js";

Then Last part calling those method inside your competent like this

const dispatch = useDispatch();
const { products } = useSelector(selectProducts);
React.useEffect(() => {
   dispatch(fetchProducts());
}, [dispatch]); 

And Finally, you can access data as products in your component.

Upvotes: 2

markerikson
markerikson

Reputation: 67469

The reducer you showed is very wrong. Reducers must never do anything async!

You don't need createAsyncThunk, but if you want to use it, it'd be like this:

export const login = createAsyncThunk(
  'login',
  ({email, password}) => firebase.auth().signInWithEmailAndPassword(email, password)
);

const authSlice = createSlice({
  name: "authSlice",
  initialState: {
    isLoggingIn: false,
    isLoggingOut: false,
    isVerifying: false,
    loginError: false,
    logoutError: false,
    isAuthenticated: false,
    user: {},
  },
  reducers: {
    /* any other state updates here */
  },
  extraReducers: (builder) => {
    builder.addCase(login.pending, (state, action) => {
      // mark something as loading here
    }

    builder.addCase(login.fulfilled, (state, action) => {
      // mark request as complete and save results
    }
  }
});

Note that createAsyncThunk only allows one argument to be passed to the thunk action creator, so it now must be an object with both fields instead of separate arguments.

Upvotes: 1

Related Questions