Home > Blockchain >  Next js - How to Update or Clear/Reset const array value?
Next js - How to Update or Clear/Reset const array value?

Time:07-12

I am Beginner to fronted development.I am working on next js project.

My task is to display result on form submit, Which i have done. Next task is to reset form and also clear/reset search result on button click. I am not able to find the solution, how do i can reset/clear that.

Here is What i have tried so far:

UPDATED

import { useForm } from 'react-hook-form';
import { useState } from "react";
import { yupResolver } from '@hookform/resolvers/yup';
import * as Yup from 'yup';

const userEndPoint = '/api/users/';
const { searchResults = [] } = [];
export default function Home() {
    const [userSearchResults, setUserSearchResults] = useState({ result: [] });
    const validationSchema = Yup.object().shape({
        searchQuery: Yup.string()
            .required('This field is required'),
    });
    const formOptions = { resolver: yupResolver(validationSchema) };
    const { errors } = formState;

    const resetFunction = async () => {
      setUserSearchResults([]);
    }

    const onSubmitFunction = async (event) => {
      console.log("search query =====> ",event.searchQuery)
      const response = await fetch(userEndPoint event.searchQuery)
      const data = await response.json()
      searchResults = data.results;
      userSearchResults = data.results;
    };
       

    return (
        <div className="card m-3">
            <h5 className="card-header">Example App</h5>
            <div className="card-body">
                <form onSubmit={handleSubmit(onSubmitFunction)}>
                    <div className="form-row row">
                        <div className="col-6 d-flex align-items-center">
                            <input name="searchQuery" type="text" {...register('searchQuery')} className={`form-control ${errors.searchQuery ? 'is-invalid' : ''}`} /> 
                            <div className="invalid-feedback">{errors.searchQuery?.message}</div>
                        </div>
                        <div className="col-6">
                        <button type="submit" className="btn btn-primary mr-1">Search</button>
                        <button type="button" onClick={() => resetFunction()} className="btn btn-secondary">Clear</button>
                    </div>
                    </div>
                    
                </form>
            </div>
            <div className="card-body">
            <p className="card-header">Search results: </p>
            {userSearchResults}
            { <ul>
                  { searchResults.map( result => {
                    const {id, name, image} = result;
                    return (
                      <li key={id} className='card'>
                        <h3>{name}</h3>
                      </li>
                    )
                  } ) }
                </ul> }
            </div>
        </div>
    );
}

Please correct me. Highly appreciated if suggest me with best practices. Thank you!

CodePudding user response:

I will assume the data returned from your API is an array of objects, please try this and let me know if that works:

export default function Home() {
  const [userSearchResults, setUserSearchResults] = useState([]);
  const validationSchema = Yup.object().shape({
    searchQuery: Yup.string().required("This field is required"),
  });
  const formOptions = { resolver: yupResolver(validationSchema) };
  const { errors } = formState;

  const resetFunction = () => {
    setUserSearchResults([]);
  };

  const onSubmitFunction = async (event) => {
    console.log("search query =====> ", event.searchQuery);
    const userEndPoint = "/api/users/";
    const response = await fetch(userEndPoint   event.searchQuery);
    const data = await response.json();
    setUserSearchResults(data.results);
  };

  return (
    <div className="m-3 card">
      <h5 className="card-header">Example App</h5>
      <div className="card-body">
        <form onSubmit={handleSubmit(onSubmitFunction)}>
          <div className="form-row row">
            <div className="col-6 d-flex align-items-center">
              <input
                name="searchQuery"
                type="text"
                {...register("searchQuery")}
                className={`form-control ${
                  errors.searchQuery ? "is-invalid" : ""
                }`}
              />
              <div className="invalid-feedback">
                {errors.searchQuery?.message}
              </div>
            </div>
            <div className="col-6">
              <button type="submit" className="mr-1 btn btn-primary">
                Search
              </button>
              <button
                type="button"
                onClick={() => resetFunction()}
                className="btn btn-secondary"
              >
                Clear
              </button>
            </div>
          </div>
        </form>
      </div>
      <div className="card-body">
        <p className="card-header">Search results: </p>
        <ul>
          {userSearchResults.length > 0 && userSearchResults.map((result) => {
            const { id, name, image } = result;
            return (
              <li key={id} className="card">
                <h3>{name}</h3>
              </li>
            );
          })}
        </ul>
      </div>
    </div>
  );
}
  • Related