Search code examples
arraysreactjsobjectjavascript-objects

How to organize fetched data in React


I fetched this data from firebase:

{-M1pSe35WgpDekyV1A6_:{cword':"শ্বশুর", wword: "শশুর"}},
{-M1pSoUng04mDi7rImUT:{cword: "শাশুড়ী", wword: "শ্বাশুড়ি"}},
{-M1pSyZ1FgiuKKjA8p2h:{cword: "ব্রাহ্মনবাড়িয়া",wword: "ব্রাম্মনবাড়ীয়া"}},
{-M1pTB2ktY8A3hk4mati:{cword: "স্টুডিও", wword: "ষ্টুডিও"}}

After using Object.values it looks like:

 [
{cword':"শ্বশুর", wword: "শশুর"},
{cword: "শাশুড়ী", wword: "শ্বাশুড়ি"},
{cword: "ব্রাহ্মনবাড়িয়া",wword: "ব্রাম্মনবাড়ীয়া"},
{cword: "স্টুডিও", wword: "ষ্টুডিও"}
]

Now I want to use the array as array[0].cword, array[1].cword.

But when I assign const somthing = array[0].cword it says cword is undefined. **This is my Component where I fetched the data : **

import React,{useState, useEffect} from 'react';
import Button from '../UI/Button/Button';
import Input from '../UI/Input/Input';
import axios from '../../axios';

import './CheckWord.css';

const CheckWord = ({}) => {
  const [state, setState] = useState({
    data: '',
    cWord:''
  });
  useEffect(()=>{
    const fetchedData = async ()=>{
      const result = await axios.get('/words.json',);
      setState({data: Object.values(result.data)});
    }
    fetchedData();
  },[]);
  // Here I want to use the state.data like **let nword = state.data[0].cword or state.data[1].cword** 
  // Submit Change Handler 
  const submitChangeHandler = (e)=>{
      e.preventDefault();
  }
  return(
    <div className='CheckWord'>
      <h4>শব্দ</h4>
      <form className='Form' onSubmit={submitChangeHandler}>
        <Input pholder='উপরের শব্দটি লিখুন' />
        <Button btnName='Submit'/>
      </form>
    </div>
  )
}

export default CheckWord;

What is the way to use cword properties consecutively ? for example: array[0].cword, array[1].cword or any other way.


Solution

  • As state={data:[...]}, you can access the values by mapping through the array

        const state={
          data: [
            {cword:"শ্বশুর", wword: "শশুর"},
            {cword: "শাশুড়ী", wword: "শ্বাশুড়ি"},
            {cword: "ব্রাহ্মনবাড়িয়া",wword: "ব্রাম্মনবাড়ীয়া"},
            {cword: "স্টুডিও", wword: "ষ্টুডিও"}
          ]
        }
    
      state.data&&state.data.map(obj=>{
            console.log(obj.cword)
        })