Home > other >  Can i pass a JSON object data values into a constant using it under useState in REACT?
Can i pass a JSON object data values into a constant using it under useState in REACT?

Time:11-12

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,

  1. Whenever you want to use data or constants from other files, you simply import them.

import jsonData from "./filePath/fileName";

  1. 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)
 }, []);


 
  • Related