I'm new to react, but I advanced a little and I'm facing an issue where I don't know how to express what I want in my code:
I have a "proxy" over my routes that saves info from the url to the apollo cache
function saveUrlVarsToCache(props) {
const LOCAL_CACHE = gql`
query localCache {
kind @client
name @client
eid @client
issueId @client
view @client
}
`
const {match} = props
// console.log( "Match path: ", match.path )
return (
<Query query={LOCAL_CACHE}>
{ /***async***/ ({data, client}) => {
const matchParams = {...(props.match.params), ...{view: Views.findViewByPath(match.path).name}}
//only override if the user types the url manually
if (data.name)
delete matchParams.name
console.log("Writing route params to local cache ", matchParams)
/***await***/ client.writeData({data: matchParams})
return <MainComp {...props}/>
}}
</Query>)
}
I call this method in every route I have
<Route exact path="/:kind"
render={saveUrlVarsToCache}>
My issue is that the comp is displayed before the apollo method client.writeData have finished.
I cannot put the return comp statement in a then clause since it will return to the then method and not to saveUrlVarsToCache.
What is weired is that even using the async await syntax (commented here), I get an error :
Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead.
in Query (at App.js:54)
in Route (at App.js:88)
in Switch (at App.js:74)
in Router (created by BrowserRouter)
in BrowserRouter (at App.js:73)
Since I need the props, I cannot call this method in the componentWillMount lifecycle method...
What to do?
p.s: I can surely rerender by calling an artificial setState({}) in the then clause of the cache saving, but this will trigger an additional render() call that I don't want
p.p.s: Maybe there's a lib for that, but I don't know what they do behind the scene so i'll avoid that for now : github.com/capaj/react-promise