Home > OS >  How to assign array within Redux AddCase fulfilled case
How to assign array within Redux AddCase fulfilled case

Time:06-29

I am having a problem trying to figure out how assign an array of users after an async fetch. I have a simple interface User, which has an id and a name:

export interface User {
  id: number
}

I then have a UserState that includes an array of users:

export interface UserState {
  loading: boolean
  users: User[] 
  status: userStatus
  error: string | null | undefined
}

In my slice, I have an asychronous function:

export const getUsers = createAsyncThunk(
  'user/fetchUsers',
  async (users: []) => {
      const response = await fetchUsers();
      return response.data;
  }
);

I don't have reducers but I do have extraReducers:

const userSlice = createSlice({
    name: 'user',
    initialState,
    reducers: {},
    extraReducers: builder => {
        builder.addCase(getUsers.fulfilled, (state, {payload: users}) => {
            state.loading = false
            state.status = 'idle'
            state.users = users  //??? Or something like this...???
            state.error = ''
        })
    }        
})

For clarity, I've just included this one addCase where I am trying to assign the expected array of users in JSON format into the users array. I've tried a number of different syntax variations and I'm getting errors like:

Type 'User[]' is not assignable to type '(() => Element)[]'. Type 'User' is not assignable to type '() => Element'. Type 'User' provides no match for the signature '(): Element'.ts(2322)

I'm not entirely sure how to address this one. I've looked at a number of tutorials and examples but there are many different ways of doing things. I'm not sure if I'm close to a solution -- there is a simple and direct fix from where I am -- or if I'm a world away from fixing this. I feel as if I've gone down too many rabbit holes and ended up creating a monster of mixed parts that don't quite fit together.

Thanks for any help!

CodePudding user response:

From the error message, it seems as if you are trying to assign a component type to the User interface here - it seems you have at some point been importing a User component instead of your User interface. Going through your imports and finding the wrong import will fix your problem.

  • Related