Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Is it okay to process data in useEffect()? #632

Closed
janhesters opened this Issue Mar 17, 2019 · 3 comments

Comments

Projects
None yet
2 participants
@janhesters
Copy link

janhesters commented Mar 17, 2019

Hi Kent,

first the TL;DR (so that you can summarize it quickly and don't have to stumble while reading it out loud, in case you answer it publicly):

Is it okay to process data in useEffect, if I make sure the effect only runs when the data changes by providing the data as a dependency? Like this:

function MyComponent() {
  const [obj, setObj] = useState(initialObj);

  useEffect(() => {
    setObj(processedData(data));
  }, [data])
}

Now the long version why I ask this question:

I recently started using react-apollo-hooks. Contrary to react-apollo this library does NOT expose a onCompleted handler. The API is pretty intuitive (see below). I need to process the result of a query, so here is what I planned on doing:

function ContactList() {
  const [contacts, setContacts] = useState([]);
  // Yes, weirdly this package exposes objects and not arrays 😅
  const { data, error, loading } = useQuery(queries.listContacts);

  useEffect(() => {
    if(!error && !loading) {
      setContacts(
        // Replaces all `null` values in list of objects with empty strings
        replaceNillInArrayWithEmptyString(data.listContacts.items)
      );
    }
  }, [data, error, loading])
 return (
  // ...
  )
}

I don't know if this is okay. It feels kinda hacky.

In any case, thank you as always! 🔥📈 🎓

@kentcdodds

This comment has been minimized.

Copy link
Owner

kentcdodds commented Mar 18, 2019

Here's the answer to your question: https://www.briefs.fm/3-minutes-with-kent/97

@janhesters

This comment has been minimized.

Copy link
Author

janhesters commented Mar 18, 2019

@kentcdodds Thank you very much! 😊

@janhesters

This comment has been minimized.

Copy link
Author

janhesters commented Mar 18, 2019

@kentcdodds Btw, great pronounciation 👌

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.