I have static data in my React app in a file called tags.js as follows:
const tagsArray = [
{
id: 1,
label: "test1"
},
{
id: 2,
label: "test2"
}]
I import this into my index.js file and use it in my App.
import tagsArray from "./tags";
ReactDOM.render(
<App data={tagsArray} />
document.getElementById("root")
);
I have a remote GraphQL service containing updated data and want to use a query to pull the array of objects and replace the static tagsArray.
I can successfully query the GraphQL data with this function:
function GQLTagFunc() {
const { loading, error, data } = useQuery(GQLTAGS);
if (loading) return <p>Loading...</p>;
if (error) return <p>Error :(</p>;
return data.tag.map(({ id, label }) => (
<div key={id}>
id:{id}, label:{label}
</div>
));
}
Which returns:
id:1, label:"test1"
id:2, label:"test2"
I know this format is incorrect but I'm not sure how to modify the function to map the data to the same format (array of objects) as tagsArray and then assign it to a variable called queriedTagsArray so I could use it in my app as follows:
<App data={queriedTagsArray} />
data.tagalready is in desired format - check network/json response if in doubt -<App data={data.tag} />?data.tagplease as currently this would error with'data' is not definedif (loading) return <p>Loading...</p>;) orif(data) return <App...GQLTagFuncyou shouldreturn <App...instead of returndata.tag.map... and<GQLTagFunc/>inside Apollo provider (instead of App) .... but to be truth you should rename it (index reactDOM.render only 'new' App... App renders Apollo with GQLTagFunc inside ... GQLTagFunc returns WrappedApp (renamed App) after reading data