Reactjs Custom Hooks ,"Cannot destructure property of null"

Im trying to create a custom hook but im constantly getting the error:
TypeError: Cannot destructure property ‘data’ of ‘Object(…)(…)’ as it is null.

Custom hook:

import axios from "axios";
import { useState, useEffect } from "react";

const useGetMethod = (Url,ImportData) => {
    const[succes,setSucces]= useState(null);
    const[loading, setLoading] = useState(true);
    const[data,setData] = useState(null)

    useEffect(() =>{
        (async () =>{
      const res = await axios.get(Url,ImportData)
      const resdata = await res.data;

if(res.status === 200){
    setSucces(true)
    setLoading(false)
    setData(resdata)
    
}
else{
    setSucces(true)
    setLoading(false)
}

        })()
            },[])

    return ( succes, loading, data );
}
 
export default useGetMethod;

were i want to show the data:

import { useState, useEffect } from "react";
import axios from "axios";
import useGetMethod from "../CustomHooks/GetMethod";

const AllProducts = () => {

     const{data, loading, succes} = useGetMethod('https://localhost:44332/api/Products/Products')

if(succes)
console.log(data)


    return (  
        <div className="AllProducts">
        <h2>All Products</h2>
</div>
    );
}
 
export default AllProducts;

the error is pointing to this code line:

const{data, loading, succes} = useGetMethod('https://localhost:44332/api/Products/Products')

You are supposed to return an object?

Return an object here.

return ( succes, loading, data );

So you can destructure it here.

const{data, loading, succes} = useGetMethod('https://localhost:44332/api/Products/Products')

yeah… that is exaclty what i have done but it doesnt work

Did you try logging the values inside the hook? It sounds like you might not be getting the expected values?

Also just as an aside, what is ImportData you do not seem to be passing a second argument to the hook when you use it.


Edit: Also, just to be absolutely clear.

You have to return:

return { succes, loading, data }

and not

return ( succes, loading, data )

As you are in the code you posted.

Thank you the () and the {} seem to be the problem,
I would also like to know how to deconstruct a Axios response,
I know how to do this with fetch but not with Axios. I am looking on google for the past couple of hours and i cannot seem to figure it out, i hope you can help me with that as well.

code:

const{data, loading, succes} = useGetMethod('https://localhost:44332/api/Products/Products')


let content;

if(loading){
    content =(
        <h4>loading please wait</h4>
    )
}else if(succes){
    content=(
        <div>
        <table width="50%">
        <tr>
          <th>Product Name</th>
          <th>description</th>
          <th>Price</th>
        </tr>
        <tr>
          <td>{data.name}</td>
          <td>{data.description}</td>
          <td>{data.price}</td>
        </tr>
      
      </table>
      </div>
    )
}else{
    <h4> error could not load products</h4>
}


    return (  
        <div className="AllProducts">
        <h2>All Products</h2>
        {content}
        
        </div>
    );
}
 

the back-end server only exist of:
name, description and price
(the spelling is correct)

{data.name} is not showing anything.

Did you log out data?

BTW, are you not getting back JSON from the API?

If so you need to use

const resdata = await res.json();

const{data, loading, succes,error} = useGetMethod(‘https://localhost:44332/api/Products/Products’)

if(succes)

console.log(“data”, data.name)

else{

console.log("no data", error)

}

I have created a error propert in hte custom hook as wel and it does not show any errors, when i do console.log(“data”, data) its shows the object. when i do console.log(“data”, data.name) its shows : data undefined. i have had the same problem with fetch but that has been solved with: a code simulair to this:

await res.json().then(function(data){console.log(data)});

Im only getting a object back from the back-end api not a string

if i use:

const resdata = await res.json();

in the custom hook i get a:
×

Unhandled Rejection (TypeError): res.json is not a function

Are you sure you are reading the shape of the object correctly? I don’t see how you can have the data object but not the properties on it. Post the object you get back so we can see it.

Also, can you post the backend code you use for the response? I assume you are using Expressjs for the backend? I don’t know why you would res a plain object why not use res.json() on the backend?

I think we might have to see your code in more detail. Do you have a Github repo you can link to?


Just FYI, I’m about to go off, I need to make some food. Maybe someone else can help you.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.