Home > front end >  Redux toolkit typescript -- what is my PayloadAction type?
Redux toolkit typescript -- what is my PayloadAction type?

Time:11-05

I'm trying to write a slice for RTK and I'm not sure what the type of my payload should be. My state -- InviteeState is an array of people objects

interface InviteeState {
  people: {
    name: string,
    age: number,
    url: string,
    note?: string
  }[]
}

Then I'm setting my initialState

const initialState: InviteeState = {
  people: [], 
}

And in my slice:

export const inviteesSlice = createSlice({
  name: "invitees",
  initialState,
  reducers: {
    // method to update state
    addInvitee: (state, action: PayloadAction<"people"[]>) => {
        state.people.push(action.payload)
    }
  }
})

But In the state.people.push(action.payload) line the action.payload is throwing the error

"Type '"people"[]' is missing the following properties from type 'WritableDraft<{ name: string; age: number; url: string; note?: string | undefined; }>': name, age, url"

I'm not sure if my PayloadAction<"people"[]> type is wrong or if my inistialState is wrong also.

How do I know what the correct type should be?

CodePudding user response:

Your payloadAction should be person object.

First declare the type for "people":

interface Person {
    // properties
}

interface InviteeState {
  people: Person[]
}

Then the initial state would be:

const initialState: InviteeState = {
  people: Person[] = [], 
}

You can use Person in your slice:

export const inviteesSlice = createSlice({
  name: "invitees",
  initialState,
  reducers: {
    // adding Person to state tree
    addInvitee: (state, action: PayloadAction<Person>) => {
        state.people.push(action.payload)
    }
  }
})

You can call that action like:

let person:Person // of course with actual data in this

dispatch(
    addInvitee(people)
)

  • Related