Tuesday 1 December 2020

Cannot update a component while rendering a different component when using QueryRender and React context

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=>
      <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=
      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.



from Cannot update a component while rendering a different component when using QueryRender and React context

No comments:

Post a Comment