I have a JSON object say something like below from a local JSON file:
export default [
{
name: "Fredrick"
age: 25,
country: "Germany"
},
{
name: "Jhonny"
age: 28,
country: "USA"
},
{
name: "Meera"
age: 26,
country: "India"
}
]
Now, how can I set it such that I can assign it within the below constant and use it within useState replacing the below hardcoded data ?
const [nodes, setNodes] = useState(
[
{
name: "Fredrick"
age: 25,
country: "Germany"
},
{
name: "Jhonny"
age: 28,
country: "USA"
},
{
name: "Meera"
age: 26,
country: "India"
}
]
);
PS: Cannot comment due to reputation.
Its simple,
import jsonData from "./filePath/fileName";
const [data, setData] = useState(jsonData);
In case your state is still null
You can define a useEffect to set the state.
useEffect(() => {
if( !data ) {
setData(jsonData)
}, []);