I am trying to use react hooks (this is my first time) but I get this error when using useEffect like the above componentDidMount: 'React Hook useEffect has a missing dependency: 'props'. Either include it or remove the dependency array. However, 'props' will change when any prop changes, so the preferred fix is to destructure the 'props' object outside of the useEffect call and refer to those specific props inside useEffect'
I'm trying to make a GET request to an API, and that needs some props in the url. This is my code:
function SomeComponent(props) {
const [data, setData] = useState({});
const [loading, setLoading] = useState(true);
const [hasError, setErrors] = useState(false);
useEffect(() => {
async function fetchData() {
try {
let response = await Axios.get( `/some-url/${props.obj.id}/abc`,
);
let { data } = response.data;
setData(data);
setLoading(false);
props.totalStats({data });
} catch (error) {
setErrors(error);
setLoading(false);
}
}
fetchData();
}, []);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
I've been looking and tried these solutions, but they don't work for me:
const { id } = props.obj.id;
const {totalStats} = props.totalStats
useEffect(()=>{
//Here is the code
//I replace the $ {props.obj.id} by the id and the function props.totalStats by //totalStats
},[id,totalStats]
Doing it that way I obtained an undefined in the id and in the call to the function.
Then I tried doing it this way:
useEffect(()=>{
//here is the code like the first one
},[props])
But this makes n number of requests to the api