fabiobh
fabiobh

Reputation: 779

How to use a map() function to show a list of elements in React with Redux Saga

I was trying to use React with Redux Saga.

The code that I use can be found here:

https://codesandbox.io/s/redux-toolkit-saga-stoic-euler-cjhgx-forked-udh3r?file=/src/App.js

When I use the code with the url below:

https://jsonplaceholder.typicode.com/todos/1

the code works for me

but I wanna use it with this url

https://jsonplaceholder.typicode.com/todos

This way I can get the list of all values

I use this code to show the information from the user/todo list

{user.title}

And it works for me

But I was not able to get the list of all values to be displayed in the app.

I try to use the code below

{user.map((parameter) => <p>1</p>)}

It says that map() is not a function.

How can I fix this?

Upvotes: 0

Views: 567

Answers (1)

Shan
Shan

Reputation: 1568

You are setting user as an object by doing setUser({...data}), Array.prototype.map can only be used for array.

Since response data is an array, you can directly set it as setUser(data)

user.js

 export function* handleGetUser(action) {
      try {
        const response = yield call(requestGetUser);
        const { data } = response; //data is an Array
        console.log('data',data);
        yield put(setUser(data));
      } catch (error) {
        console.log(error);
      }
    }

userSlice.js

const userSlice = createSlice({
  name: "user",
  initialState: {},
  reducers: {
    getUser() {},
    setUser(state, action) {
      const userData = action.payload; //setting userData (Array) as data
      return { ...state, data:userData };
    }
  }
});

App

return (
    <div className="App">
      {user.data.length}
      {user.data?.map((obj) => <h1 key = {obj.id}>{obj.id}.{obj.title}</h1>)}
    </div>
  );

Upvotes: 2

Related Questions