Accessing Object ReactJS

Viewed 63

I'm trying to get the data from this API to show up and I cant for the life of me figure out a way for it to work. I can get the sol_keys to show up but that's it. My original thought would be "average temp" is something like {sol.AT.mx} and so on for the others but no go. Any help is much appreciated.

Here is the code:

const Weather = () => {
  const { data, status } = useQuery("weather", fetchWeather);
  console.log(data);

  return (
    <div>
      <h2>Mars Weather</h2>

      {status === "loading" && <div>Loading Data...</div>}

      {status === "error" && <div>Error Fetching Data</div>}

      {status === "success" && (
        <div>
          {" "}
          {data.sol_keys.map((sol) => (
            <div>Sol: {sol}</div>
            <div>Average Temp: ??? </div>
            <div>Wind Direction: ??? </div>
            <div>Season: ??? </div>
          ))}
        </div>
      )}
    </div>
  );
};

Here is the what the API returns. API Response

1 Answers

If I understand correctly, you're looking for a way to access "sol" data (on the numeric keys in data) and render that to a list of <div> elements where each <div> contains the "sol" content.

A simple solution would be to iterate the sol_keys sub-array of data, and use the sol_key (see below) to access the corresponding sol_value from data. We can combine this process into a single mapping as shown below:

{ status === "success" && (
    <div>
    { data.sol_keys.map((sol_key, index) => {

      /* Extract sol_value from data, for current sol_key */
      const sol_value = data[sol_key]

      /* Add index as key to each item of list being rendered */
      return  <div key={index}>
            {" "}
            <div>Sol:</div>
            <div>Average Temp: 
            { /*
            Just rendering nested objects as JSON string - 
            update this to suit your specific presentation
            requirements 
            */ }
            { JSON.stringify(sol_value.AT) } 
            </div>
            <div>Wind Direction: 
            { JSON.stringify(sol_value.WD) } 
            </div>
            <div>Season: 
            { sol_value.season } 
            </div>
        </div>      
        })
    }
    </div>
)}

The way actual temperature and wind direction data is presented is up to you, however hopefully this gives you a good starting point that solves the initial problem :-)

Related