Reputation: 644
I'm trying to access the Contacts from the state but I'm always getting the whole state.
I've tried destructuring but that doesn't work either?
My slice contains toolkit and thunk.
export interface Contact {
name: string;
phone: string;
id: number;
}
export interface contactSliceState {
contacts: Contact[];
status: "idle" | "pending" | "succeeded" | "failed";
loading: boolean;
}
const contacts: Contact[] = useSelector<contactSliceState, Contact[]>(
(state) => state.contacts
);
console.log("contacts", contacts)
contacts:
0: {name: "John", phone: "123012", id: 1}
1: {name: "Bill", phone: "653722", id: 2}
2: {name: "Tom", phone: "874932", id: 3}
loading: false
status: "succeeded"
Upvotes: 0
Views: 221
Reputation: 16576
It seems like you might be giving the Typescript compiler incorrect information about the shape of your state. Since contacts
is just a slice, you should provide the shape of the root state as the first generic to useSelector
. Then I believe it will make a lot more sense:
const contacts = useSelector<RootState, Contact[]>(
(state) => state.contacts.contacts
);
Note that what I'm calling the "root" state is just the top-level state including all slices (I'm assuming the contacts
is a key of the top-level state.
Upvotes: 3