Reputation: 146
Is there a way to add dependencies and prevent it to reload the state when they change?
Error: Line 48:6: React Hook useEffect has missing dependencies: 'profile.bio', 'profile.company', 'profile.githubusername', 'profile.location', 'profile.skills', 'profile.social', 'profile.status', and 'profile.website'. Either include them or remove the dependency array. If 'setFormData' needs the current value of 'profile.company', you can also switch to useReducer instead of useState and read 'profile.company' in the reducer react-hooks/exhaustive-deps
Code:
useEffect(() => {
getCurrentProfile();
setFormData({
company: loading || !profile.company ? "" : profile.company,
website: loading || !profile.website ? "" : profile.website,
location: loading || !profile.location ? "" : profile.location,
status: loading || !profile.status ? "" : profile.status,
skills: loading || !profile.skills ? "" : profile.skills.join(","),
githubusername:
loading || !profile.githubusername ? "" : profile.githubusername,
bio: loading || !profile.bio ? "" : profile.bio,
twitter: loading || !profile.social ? "" : profile.social.twitter,
facebook: loading || !profile.social ? "" : profile.social.facebook,
linkedin: loading || !profile.social ? "" : profile.social.linkedin,
youtube: loading || !profile.social ? "" : profile.social.youtube,
instagram: loading || !profile.social ? "" : profile.social.instagram,
});
}, [loading, getCurrentProfile]);
For some reason it doesn't stop warning me of the "Missing dependencies" if I don't add: "[ loading, getCurrentProfile, profile.bio, profile.company, profile.githubusername, profile.location, profile.skills, profile.social, profile.status, profile.website, ]
But as you might have guessed useEffect doesn't behave well when you add a dependency linked to what's been changed. Not allowing to edit the fields.
TL;DR when I add the asked dependencies it keeps re-updating the state of my fields, not letting the user edit them.
Upvotes: 0
Views: 230
Reputation: 11176
Ciao, you could use useRef
hook in this way:
import React, { useEffect, useRef } from 'react';
...
const justOneTime = useRef(true)
useEffect(() => {
if (justOneTime.current) {
// your logic
justOneTime.current = false
}
}, [/*all the dependencies that useEffect needs*/])
In this way, even if one of the dependencies change his value, useEffect code (inside the if statement) will be executed just one time.
Upvotes: 1