Skip to content
This repository has been archived by the owner. It is now read-only.

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

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

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

janhesters opened this issue Mar 17, 2019 · 3 comments

Comments

@janhesters
Copy link

@janhesters 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
Copy link
Owner

@kentcdodds kentcdodds commented Mar 18, 2019

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

@janhesters
Copy link
Author

@janhesters janhesters commented Mar 18, 2019

@kentcdodds Thank you very much! 😊

@janhesters
Copy link
Author

@janhesters janhesters commented Mar 18, 2019

@kentcdodds Btw, great pronounciation 👌

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Linked pull requests

Successfully merging a pull request may close this issue.

None yet
2 participants