Ayo Adesina
Ayo Adesina

Reputation: 2415

Nextjs - How to redirect user to another page based on a fetch request

I have a nextjs page with a form, the user will submit a post code.

The page then makes a fetch request to an API end point and gets a JSON result.

I want redirect the user to a diffrent page inside my nextjs website based on the result of that API call.

This is what I have so far: (FORM)

 <form onSubmit={submitPostCode}>
                                    <input className={style.inputfield}
                                        type="text"
                                        id="postCode"
                                        name="postCode"
                                        placeholder="What's your post code?"
                                        required />

                                    <button type="submit" className={style.findMyAddressBtn}>
                                        FIND MY ADDRESS
                                    </button>
                                </form>

Click Handler:

const submitPostCode = async (event) => {

    try {
        const router = useRouter();

        event.preventDefault();
        const postCode = event.target.postCode.value;
        const res = await fetch(`https://api.postcodes.io/postcodes/${postCode}`);
        const result = await res.json();

        router.push('/some-path/' + result.area);

    } catch (e) {
    }
   
};

Upvotes: 0

Views: 1275

Answers (1)

H9ee
H9ee

Reputation: 420

let's try this code:

const router = useRouter();

const submitPostCode = async (event) => {
        event.preventDefault();
    try {
        const postCode = event.target.postCode.value;
        const res = await fetch(`https://api.postcodes.io/postcodes/${postCode}`);
        const result = await res.json();
        if(result.area){
          router.push(`/some-path/${result.area}`);
        }else{
          console.log("failed to redirect")
        }
       

    } catch (error) {
      console.log(error)
    }
   
};

Upvotes: 0

Related Questions