Home > Blockchain >  How to bind an input's value to a link in react
How to bind an input's value to a link in react

Time:04-28

I want to create a simple application where you can search for images. The application is written in React using fetch (I can't use axios) and Unsplash API. My current attempt renders a list of images with a static value "cars" into the link as shown: https://api.unsplash.com/search/photos?query=**cars** In the code example below I am using a variable "${query}" to be able to search for images but it toes not work. I need help to figure out how to fix that. Thanks in advance!

code:

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

export default function App() {
  const [data, setData] = useState(null);
  const [error, setError] = useState(null);
  const [query, setQuery] = useState("");

      useEffect(() => {
        fetch(`https://api.unsplash.com/search/photos?query=${query}`, {
          headers: {
            Authorization: "Client-ID UnsplashId",
          },
        })
          .then((response) => {
            if (!response.ok) {
              throw new Error(
                `This is an HTTP error: The status is ${response.status}`
              );
            }
            return response.json();
          })
          .then((actualData) => {
            console.log(actualData);
            setData(actualData.results);
            setError(null);
          })
          .catch((err) => {
            setError(err.message);
            setData(null);
          });
      }, []);
    
      return (
        <div>
          {/* onSubmit={this.handleSubmit} */}
          <form>
            <label>
              <input
                placeholder="Search"
                type="text"
                // value={this.state.value}
                // value="cars"
                onChange={(e) => setQuery(e.target.value)}
              />
            </label>
            <input type="submit" value="Submit" />
          </form>
    
          {data &&
            data.map(({ id, description, urls }) => (
              <img key={id} alt={description} src={urls.regular} />
            ))}
        </div>
      );
    }

CodePudding user response:

I think you want to achieve conditionally firing an effect

Example


 useEffect(() => {

    // This will execute whenever 'query' variable changes.       
 
 }, [ query ]);
    

// You can bind the state using the 'value' attribute.

<input 
   placeholder="Search"
   type="text"
   value={query}
   onChange={(e) => setQuery(e.target.value)}
/>

CodePudding user response:

I did not quietly get the question but I think you want to do the search every time the input is changed, hence I recommend using an input instead of the form and adding "query" to the "useEffect" conditions:

   useEffect(() => {
    fetch(`https://api.unsplash.com/search/photos?query=${query}`, {
      headers: {
        Authorization: "Client-ID UnsplashId",
      },
    })
      .then((response) => {
        // here
  }, [query]);

<input
     placeholder="Search"
     type="text"
     onChange={(e) => setQuery(e.target.value)} />
  • Related