Trying to work with asyncSagas to fetch and display array of items and manipulating them in different components. Struggling to understand how?

I am trying to fetch some data from an API, then storing that data and providing it to different components so that they can dynamically manipulate it. I am, however, absolutely struggling to understand how Redux operates, what's the best way to do it and how it works with React Toolkit. I am absolutely obsessed in trying to learn and understand how all of this works, but at the moment the more docs I read I get more confused. Based on my current understanding I have set up a store.js file and configured it:

import { configureStore } from "@reduxjs/toolkit";
import PeopleReducer from "./peopleSlice";
export default configureStore({
  reducer: {
    app: PeopleReducer,
  },
});

I then have another file that should fetch me the data from the API:

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


export const fetchPeople = createAsyncThunk(
    "people/fetchPeople",
    async () => {
      return fetch(
        "https://swapi.dev/api/people"
      ).then((res) => res.json());
    }
  );


  const peopleSlice = createSlice({
    name: "people",
    initialState: {
      people: [],
      person: {},
    }
  });

  export default peopleSlice.reducer;

After that a component that should receive the fetched API data:

const PeopleList = () => {
  const { people, loading } = useSelector((state) => ({ ...state.app }));
  const dispatch = useDispatch();

  useEffect(() => {
    dispatch(fetchPeople());
    console.log(people);
  }, []);

  return <div>{people.map(person => {
      return <p>{person.name}</p>
  })}</div>;
};

However, I can't quite understand how that fetched and stored data is supposed to be accessed and manipulated by different components and rendered dynamically, when for example it's filtered within one of the components. Any pointers is much appreciated.

1 answer

  • answered 2022-05-07 08:20 phry

    You are fetching the data with your fetchPeople thunk (not saga btw.), but that data is never getting stored - that would be the job of your peopleSlice.

    That fetchPeople thunk will dispatch up to three actions:

    • a pending action when it starts
    • a fulfilled action when it succeeds
    • a rejected action when it fails

    so if you want to save that data, you have the slice react to the fulfilled action:

    
    
      const peopleSlice = createSlice({
        name: "people",
        initialState: {
          people: [],
          person: {},
        },
        reducers: {},
        extraReducers: builder => {
          builder.addCase(fetchPeople.fulfilled, (state, action) => {
            state.people = action.payload
          })
        }
      });
    

    Give this tutorial chapter a thorough read.

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum