1

I'm trying to get data based on the search from API, with React/Axios

        process.env.REACT_APP_MARVEL_API_BASE_URL +
          'characters?nameStartWith=${query}orderBy=name' +
          '&ts=' +
          ts +
          '&apikey=' +
          process.env.REACT_APP_MARVEL_API_PUBLIC_KEY +
          '&hash=' +
          hash
      )

query - must be dynamic so with every search I must replace search value with query. it's my first react project tho.

This is the Search Component:


const Search = ({ getQuery }) => {
  const [text, setText] = useState('')

  const onChange = (q) => {
    setText(q)
    getQuery(q)
  }

  return (
    <section className="search">
      <form>
        <input
          type="text"
          className="form-control"
          placeholder="Search e.g. Ironman, Stan Lee"
          value={text}
          onChange={(e) => onChange(e.target.value)}
          autoFocus
        ></input>
      </form>
    </section>
  )
}

export default Search

this is Main Application:

import axios from 'axios'
import Header from './components/ui/Header'
import CharacterGrid from './components/characters/CharacterGrid'
import Search from './components/ui/Search'
import crypto from 'crypto'
import './App.css'

const ts = new Date().getTime
const hash = crypto
  .createHash('md5')
  .update(
    ts +
      process.env.REACT_APP_MARVEL_PRIVATE_KEY +
      process.env.REACT_APP_MARVEL_API_PUBLIC_KEY
  )
  .digest('hex')

const App = () => {
  const [items, setItems] = useState([])
  const [isLoading, setIsLoading] = useState(true)
  const [query, setQuery] = useState('')

  useEffect(() => {
    const fetchItems = async () => {
      setIsLoading(true)
      const result = await axios(
        process.env.REACT_APP_MARVEL_API_BASE_URL +
          'characters?nameStartWith=${query}orderBy=name' +
          '&ts=' +
          ts +
          '&apikey=' +
          process.env.REACT_APP_MARVEL_API_PUBLIC_KEY +
          '&hash=' +
          hash
      )

      setItems(result.data)
      setIsLoading(false)
    }
    fetchItems()
  }, [query])

  return (
    <div className="container">
      <Header />
      <Search getQuery={(q) => setQuery(q)} />
      <CharacterGrid isLoading={isLoading} items={items} />
    </div>
  )
  //TODO pagination
}

export default App

but search not working, the ${query} syntax neither highlighting nor working

2

1 Answer 1

1

It looks like you're using ' (single quote) instead of ` (grave accent) to wrap your template literals

'characters?nameStartWith=${query}orderBy=name'

should be

`characters?nameStartWith=${query}orderBy=name`
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.