Home > Mobile >  How to define TypeScript types when used with React useState and the previous state inside a state u
How to define TypeScript types when used with React useState and the previous state inside a state u

Time:12-02

I am pretty new to development and need some help—and patience. I'm converting a React project to TypeScript and having some issues managing and updating the state inside my Context component.

I'm building a log viewer that displays a series of tasks and their nested sub-tasks, depending on which task is selected.

The events are defined in an Event class which is populated with data from a custom useFetch hook. These are stored as objects inside Event arrays. When a task is selected, it is stored in a currently 'selectedTask' state and must also be pushed into a 'Hierarchy' array.

The idea is to display a hierarchy of subsequently selected tasks, as the user clicks through multiple nested layers of task logs.

These events are defined inside a type 'ContextObject' as follows:

    hierarchy: Event[] | undefined
    setHierarchy: Dispatch<SetStateAction<Event[] | undefined>>
    selectedSubEvent: Event[];
    setSelectedSubEvent: Dispatch<SetStateAction<Event[]>>;

They are managed via useState:

    const [hierarchy, setHierarchy] = useState<Event[] | undefined>([]);
    const [selectedSubEvent, setSelectedSubEvent] = useState<Event[]>([]);

In order to update the hierarchy with the selected task, I'm using a state updating function inside a useEffect as follows, and getting an error on the '...prevState':

    useEffect(() => { 
        setHierarchy((prevState) => [...prevState, selectedSubEvent])
    }, [selectedSubEvent]);

The error I'm getting:

    Type 'Event[] | undefined' is not an array type.ts(2461)
    (parameter) prevState: Event[] | undefined

When I forgo the state update function inside the useEffect and just set 'Hierarchy' to the 'selectedEvent', it does set that single event to the hierarchy, but obviously I need more than that.

I've also tried checking the prevState before spreading it, but that gave multiple errors:

    setHierarchy((prevState) =>
        prevState ? [...prevState, selectedSubEvent] : [selectedSubEvent]
        );

//Errors
Argument of type '(prevState: Event[] | undefined) => (Event | Event[])[]' is not assignable to parameter of type 'SetStateAction<Event[] | undefined>'.
  Type '(prevState: Event[] | undefined) => (Event | Event[])[]' is not assignable to type '(prevState: Event[] | undefined) => Event[] | undefined'.
    Type '(Event | Event[])[]' is not assignable to type 'Event[]'.
      Type 'Event | Event[]' is not assignable to type 'Event'.
        Type 'Event[]' is missing the following properties from type 'Event': key, id, startTime, endTime, and 3 more.ts(2345)

I realise I'm not providing much in the way of what I've tried, but I have tried countless articles, tutorials and both the React and TypeScript documentation and I'm at a loss

  • Related