Home > front end >  Change object parameter by useState() in ReactJS
Change object parameter by useState() in ReactJS

Time:02-12

So I'm trying to change an object parameter that is being called by .map inside curly braces. Here is the code:

import React, { useEffect, useState } from 'react'

function App() {
  const [news, setNews] = useState([])
  const [searchQuery, setSearchQuery] = useState('city')

  const getNews = () => {
    fetch('https://api.randomuser.me/?nat=USA&results=5')
      .then(result => result.json())
      .then(data => setNews(data.results))
      .then(error => console.log(error))
  }

  const handSearch = (e) => {
    setSearchQuery(e.target.value)
  }

  //the [] at the end is enabled to request data only onces
  useEffect(() => {
    getNews()
  }, [searchQuery])
  
  return (
    <div>
      <form>
        <input onChange={handSearch}></input>
      </form>
      <p><b>Available Input: </b>city, state, country, postcode</p>
      <hr/>
      {
        news.map((value, index) => (
          <p key={index}>{`value.location.${searchQuery}`}</p>
        ))
      }
      <p>{searchQuery}</p>
    </div>
  );
}

export default App;

But it doesn't work, it only return a string. I've tried to :

  1. Remove the Apostrophe ``
  2. Change the curly braces to another brackets []
  3. Make a const outside return() just for value.location.${searchQuery} and put it back to the curly braces
  4. Some other small changes I kinda forgot

How to complete an object parameter by ${}?

Any help would be appreciated, thanks before!

CodePudding user response:

change this line of your code

<p key={index}>{`value.location.${searchQuery}`}</p>

to this

<p key={index}>{value.location[searchQuery]}</p>

it is gonna work.

read this article dynamic key it's gonna help you.

CodePudding user response:

You need to use square brackets to get the computed value of searchQuery value.location[searchQuery]

For example:

import React, { useEffect, useState } from 'react';

function App() {
  const [news, setNews] = useState([])
  const [searchQuery, setSearchQuery] = useState('city')

  const getNews = () => {
    fetch('https://api.randomuser.me/?nat=USA&results=5')
      .then(result => result.json())
      .then(data => setNews(data.results))
      .then(error => console.log(error))
  }

  const handSearch = (e) => {
    setSearchQuery(e.target.value)
  }

  //the [] at the end is enabled to request data only onces
  useEffect(() => {
    getNews()
  }, [searchQuery])
  
  return (
    <div>
      <form>
        <input onChange={handSearch}></input>
      </form>
      <p><b>Available Input: </b>city, state, country, postcode</p>
      <hr/>
      {
        news.map((value, index) => (
          <p key={index}>{value.location[searchQuery]}</p>
        ))
      }
      <p>{searchQuery}</p>
    </div>
  );
}

export default App;
  • Related