discodowney
discodowney

Reputation: 1507

useState Hook with JSX

I have the following custom hook in a .tsx file:

import {useCallback, useState} from 'react';

const useHttp = (requestObj: any, setData: Function) => 
{
    const [isLoading, setIsLoading] = useState(false); 
    const [error, setError] = useState(null);
    const [elements, setElements] = useState(null);
    
    const sendRequest = useCallback(() =>
    {
        setIsLoading(true);
        setError(null);
        fetch(requestObj.url)
            .then(res => res.json())
            .then(data => {
                setIsLoading(false);
                setData(data);
                let jsx = (<div>Testing conor</div>)
                setElements(jsx);
            })
            .catch(err => 
            {
                setError(err.message);
                setIsLoading(false);
                console.log('There was an error');
            });
    }, []);

    return {
        isLoading: isLoading,
        error: error,
        elements: elements,
        sendRequest: sendRequest
    }
} 

export default useHttp;

When I call setElements my IDE is saying there is an error when I call setElements.

let jsx: JSX.Element
Argument of type 'Element' is not assignable to parameter of type 'SetStateAction<null>'.
  Type 'Element' provides no match for the signature '(prevState: null): null'.ts(2345)

the code works fine so I jst want to know why the ide is saying its a problem

Upvotes: 1

Views: 3376

Answers (1)

Nicholas Tower
Nicholas Tower

Reputation: 84902

const [elements, setElements] = useState(null);

Since you havn't given an explicit type to this state, typescript will infer it from usage. It sees you initialized the state with null, and so it assumes the state is (and always will be) null

To let the state change to something ther than null, you'll need to be explicit about the type. If you're storing elements in state, then that type would be:

const [elements, setElements] = useState<JSX.Element | null>(null)

Upvotes: 3

Related Questions