简体   繁体   中英

Redux toolkit typescript -- what is my PayloadAction type?

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?

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)
)

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