I am very new to React hooks. I have previously used class based components in react and using methods like setState
. However this is the first time I am using React Hooks with function based components. So probably not the correct title either. Here is the explanation what I am trying to do. I am trying to create a dataModel
which will contain all the data fetched using different apis. Then this model will be passed to different components. This dataModel
will be created when the page initially loads. In the below code I am declaring a variable dataModel
which will contains keys
and each key
will have an array or dictionary. I tried few options but it is not working. I have put the code which I tried. I would appreciate the help which would fix it.
import './App.css';
import Query from './components/landing/query';
import React, {useState,useEffect} from 'react';
function App() {
const [dataModel,setDataModel] = useState({
yearOptions: [],
locOptions: []
})
const fetchYear = async()=>{
await fetch(
"http://localhost:3002/getYear"
).then((response)=>response.json())
.then((data)=>{
setDataModel(
data.map((x)=>{
let eachx = {key:x.key, text:x.value,value:x.value}
dataModel.yearOptions.concat(eachx)
})
)
})
}
const fetchLoc = async()=>{
await fetch(
"http://localhost:3002/getYear"
).then((response)=>response.json())
.then((data)=>{
setDataModel(
data.map((x)=>{
let eachx = {key:x.key, text:x.value,value:x.value}
dataModel.locOptions.concat(eachx)
})
)
})
}
useEffect(() => {
fetchYear();
fetchLoc();
}, []);
return (
<div className="App">
<header className="App-header">
React Based FrontEnd and Nodejs Based Rest API Demo Project
</header>
<Query props={{model:dataModel}}/>
</div>
);
}
export default App;