typedefs for useState across components with object arrays

We have a Parent and a Child component. inside of parent we init the following state:
const [objects, setObjects] = useState<
{ url: string; partNumber: number }[]>([]);
const [objects, setObjects] = useState<
{ url: string; partNumber: number }[]>([]);
we want this state to be shared between our two components inside of Parent we render a Child passing the state as props
<Child objects={objects} setObjects={(e) => setStateHelper(e)} />
<Child objects={objects} setObjects={(e) => setStateHelper(e)} />
inside of our Child component we define our props and eventually we may want to update the state.
const Child = ({objects, setObjects}: {objects: {url: string, partNumber: number }[]; setObjects: (e: { url: string, partNumber: number}[]) => void; }) => {
... component does stuff, eventually we want to update the state
setObjects(newObject)
}
const Child = ({objects, setObjects}: {objects: {url: string, partNumber: number }[]; setObjects: (e: { url: string, partNumber: number}[]) => void; }) => {
... component does stuff, eventually we want to update the state
setObjects(newObject)
}
Right now I am getting an trying to create a helper function in the parent component so I don't have do deal with the setState types, eg.
Dispatch<SetStateAction<{
url: string;
partNumber: number;
}[]>>
Dispatch<SetStateAction<{
url: string;
partNumber: number;
}[]>>
in the child component The current one I have looks like the following:
const setStateHelper = (urls: { url: string; partNumber: number; }[]) => {
setObjects((prevState) => [...prevState, urls]);
}
const setStateHelper = (urls: { url: string; partNumber: number; }[]) => {
setObjects((prevState) => [...prevState, urls]);
}
The problem is that I am getting a ts(2345) error, a type mismatch. Argument of type '(prevState: { url: string; partNumber: number; }[]) => ({ url: string; partNumber: number; } | { url: string; partNumber: number; }[])[]' is not assignable to parameter of type 'SetStateAction<{ url: string; partNumber: number; }[]>'.
1 Reply
JulieCezar
JulieCezar2y ago
Did you try ...urls?
const setStateHelper = (urls: { url: string; partNumber: number; }[]) => {
setObjects((prevState) => [...prevState, ...urls]);
}
const setStateHelper = (urls: { url: string; partNumber: number; }[]) => {
setObjects((prevState) => [...prevState, ...urls]);
}
Want results from more Discord servers?
Add your server