5

I am having an issues I can't seem to work out. When I use the QueryRenderer HOC component from relay and render it as children via a react context I get the following error:

Cannot update a component (`Customers`) while rendering a different component (`Search `). To locate the bad setState() call inside `Search`, follow the stack trace as described in https://reactjs.org/link/setstate-in-render

My context and component are very simple. As soon as I replace the QueryRenderer the problem goes away, so I am 100% certain this HOC component is causing the issue.

//context
const SearchProvider = ({ getVariables, query, children }) => {
  const [searchTerm, setSearchTerm] = useState()
  return (
    <SearchContext.Provider value={{ searchTerm, setSearchTerm }}>
      <Search getVariables={getVariables} query={query}>
        {children}
      </Search>
    </SearchContext.Provider>
  )
}
//component causing the error
const Search = ({ getVariables, query, setRetry, children }) => {
  const { searchTerm } = useSearch()
  return (
    <QueryRenderer
      environment={environment}
      query={query}
      variables={{ ...getVariables(searchTerm) }}
      render={({ error, props, retry }) => children({ error, props, retry })}
    />
  )
}
//and for context the component that is rendering the SearchProvider component
const Customers = () => {
  const getVariables = searchTerm => {
    //work out and return variables
  }
  return (
    <>
      <h1 className="text-xl mb-2">Customers</h1>
      <SearchProvider query={query} getVariables={getVariables}>
        {({ error, props }) => {
          if (error) return <Error />
          if (!props) return <Loading />
          return (
            <ul className="flex flex-wrap w-full mt-4">
              {props.users_connection.edges.map(({ node }) => (
                <Customer key={node.userId} customer={node} />
              ))}
            </ul>
          )
        }}
      </SearchProvider >
    </>
  )
}

Any suggestions or tips are greatly appreciated. For now I am simply living with the error. I haven't noticed it impacting performance or introducing any bugs.

I have tried moving the QueryRenderer component directly in the SearchProvider component and it didn't make any difference.

2

0

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.