0

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!

6
  • useForm provides you with a reset function, maybe that's what you are looking for? You can check it out here Commented Jul 12, 2022 at 6:35
  • reset will clear only form inputs, I have to clear/reset the searchResult array. when I just want to reset/clear/empty search results that is getting fetched from api. Commented Jul 12, 2022 at 6:40
  • For that it would be a better approach to use a state instead, e.g. const [searchResults, setSearchResults] = useState([]); then inside your reset function you can clear the array like: setSearchResults([]);, you'd need to modify your submit function accordingly too when setting this state with the data coming from your API. Commented Jul 12, 2022 at 6:45
  • thanks for suggestion, i tried your way it is giving error Objects are not valid as a React child Commented Jul 12, 2022 at 7:27
  • Can you edit the question and add those changes? that way I could assist you further. Commented Jul 12, 2022 at 7:29

1 Answer 1

1

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>
  );
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much for your time and helping me out. Highly appreciated (y)

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.