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"
}
]
);
CodePudding user response:
PS: Cannot comment due to reputation.
Its simple,
- Whenever you want to use data or constants from other files, you simply import them.
import jsonData from "./filePath/fileName";
- Now simply, you can assign it to the useState like
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)
}, []);