1

Some how match data is from the parent class, and I initialized matches using useState(match) However, matches data is containing old data and wasn't updated as parent match data. Anyone help?

const FixtureDetailItem = ({ type, match, teams, isAdmin, postMatchesStart, putMatchesStart }) => {
  console.log(match)
  const [matches, setMatches] = useState(match);
  const { homeTeamId, homeTeamName, homeScore, awayTeamId, awayTeamName, awayScore, scheduledAt, location, league, matchRecords} = matches;

  useEffect(() => {
    console.log('fired')
    console.log(matches)
    setMatches(matches)
  }, [matches]);
2
  • You're doing something wrongly. When matches is changed the effect going to re-fire because matches is its dependency. Commented Feb 8, 2020 at 23:35
  • Also instead of setMatches(matches) use setMatches({ ...matches }). Commented Feb 8, 2020 at 23:35

1 Answer 1

1

There seems to be a circular connection between useEffect() and the useState - useEffect has a dependency of matches, then sets matches.

If you want it to change when match changes, then match should be the dependency.

Note that useState(match) only fires on the very first render. On subsequent renders, you must use setMatches() to change the value of matches.

const FixtureDetailItem = ({ type, match, ... }) => {

  const [matches, setMatches] = useState(match);
  const { ... } = matches;

  useEffect(() => {
    setMatches(match)
  }, [match]);

  ... // JSX here

}

@James I though this might need some clarification.

See my statement above - useState(match) only fires on the very first render.

On first render useState(match) sets matches equal to match.

Then the parent changes match, and because the match prop changed, the FixtureDetailItem function runs again, but React does not run useState(match) for the new value (by design).

It considers matches to be internal state of this component and leaves it with the old value.

Since matches does not change, the effect will not run - it only runs when one of it's dependencies change.

Sign up to request clarification or add additional context in comments.

4 Comments

How can it be possible to implement internal state to use new value? once match is changed?
With setMatches() - that's what the useEffect() is doing.
by understanding what you've mentioned "It considers matches to be internal state of this component and leaves it with the old value" above code seems leave internal matches state with the old value, so child component isn't updated. Doesn't it?
No setMatches() can change it, but of course needs to be explicitly called.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.