Skip to content
Advertisement

What is the correct way for getting data from this object in ReactJS?

I’ve got ReactJs who is getting response from backend server. console.log(content) is looking like this:

{
    "data": {
        "dataNKS": [
            75670.99,
            75654.97,
            75943.38
        ],
        "dataMNKS": [
            37835.5,
            37827.49,
            37971.69
        ],
        "dataEKS": [
            75871.73,
            75816.11,
            76062.19
        ],
        "dataMEKS": [
            37935.86,
            37908.05,
            38031.1
        ]
    },
    "id": "32083654",
    "descr": "articleno1",
    "price": "75.284",
    "link": "/linkno1",
    "sqm": "75",
    "ppm2": "2151"
}

Now in my react app I can easily access to data with {content.price} eg. and I will get 75.284.

Now trouble I’ve got is when accessing content.data. I can access to data and console.log it, where data is formatted like this:

{dataNKS: Array(3), dataMNKS: Array(3), dataEKS: Array(3), dataMEKS: Array(3)}

Now my question is how to access each data and output it? Desired look in React app would be to output value of dataNKS + dataMNKS and under it dataEKS + dataMEKS eg. 75670 - 37835.5 – this is first entries of arrays dataNKS and dataMNKS. I’ve tried

const a = content.data;
return(
<div className ='container'>
{a.map((item, i) => (
          <li key={i}>
            {item.dataEKS}
            {item.dataMEKS}
          </li>
        ))}
</div>
);
-------Eror Cannot read property 'map' of undefined----------
<div className='container'>
          {Object.keys(a).map((keyName, i) => (
            <div key={i}>
              <strong>Name: {a[keyName]}</strong>
            </div>
          ))}
        </div>
-------Error Cannot convert undefined or null to object-------

and few other methods but without success. What is correct way of displaying data from this object?

EDIT: Requested part of getting content:

const [content, setContent] = useState([]);

useEffect(() => {
    const fetchPosts = async () => {
      const id = props.match.params.id;
      const res = await ArticleService.article(id);
      setContent(res.data);
    };
    fetchPosts();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

and after this I can console.log(content)

Advertisement

Answer

It is correct in your second code.There are only one error you need to handle:

Cannot convert undefined or null to object

you can resolve it by this:

<div className='container'>
 {a&&Object.keys(a).map((keyName, i) => (
   <div key={i}>
     <strong>Name: {a[keyName]}</strong>
   </div>
 ))}
</div>
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement