简体   繁体   中英

Data fetched from axios is storing inside an additional Array without a reason

I am fetching below data from mongo:

"data": [
        {
            "_id": "5ee3f064344d21fb2645f5c0",
            "name": "John",
            "surname": "Doe",
            "email": "john@gmail.com",
            "createdAt": "2020-06-12T21:15:16.624Z",
            "__v": 0
        },
        {
            "_id": "5ee5e27f1ecd8f05ad764057",
            "name": "Jane",
            "surname": "Doe",
            "email": "jane@gmail.com",
            "createdAt": "2020-06-14T08:40:31.701Z",
            "__v": 0
        }

I am using axios to fetch the data. Below is my code that is fetching the data:

async function getUser() {
    const user = await axios.get('/api/plugins/users');

    dispatch({
      type: 'GET_USER',
      payload: user.data.data,
    });
  }

Data is all good, but the problem is that I am getting the data Array inside another Array and I am not sure how.

Here is what I am getting:

[
  [
    {"_id":"5ee3f064344d21fb2645f5c0","name":"John","surname":"Doe","email":"john@gmail.com","createdAt":"2020-06-12T21:15:16.624Z","__v":0},
{"_id":"5ee5e27f1ecd8f05ad764057","name":"Jane","surname":"Doe","email":"jane@gmail.com","createdAt":"2020-06-14T08:40:31.701Z","__v":0}
  ]
]

This is my Initial State and reducer, both are in separate files:

const initialState = {
  users: [],
  loading: true,
};

case 'GET_USER':
      return {
        ...state,
        users: [...state.users, action.payload],
        loading: false,
      };

This seems very odd to me and I am not sure what is causing it to put the data inside another array. Can someone please take a look.

action.payload is an array. state merging is wrong in

case 'GET_USER':
      return {
        ...state,
        users: [...state.users, action.payload], //it's wrong.It will create nested array
        loading: false,
      };

it should be

users: [...state.users, ...action.payload], // spread array element in users  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM