kabison33
kabison33

Reputation: 111

React Router <Link /> - how to execute onclick on page refresh?

Can y'all coding experts help me with this please..

The code is shown below.

I am trying to implement a simple search page. You will be redirected to this page containing the answer from the search criteria that you input in a previous page. In this current page, you can also modify the answer that you got by inputting a new search criteria, then you click search to get a new answer, replacing the old one. Ideally when inputting a new search criteria, it should replace the old querystring in the url of the page, and then the page will refresh, and then the new query string is used to get the new answer, which will be displayed in the refreshed page. So here is what i write.

import React from 'react';
import { Link } from 'react-router-dom';
const querystring = require('querystring');

class SearchResult extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            answer: '',
            input: '',
        };
        this.getEntries = this.getEntries.bind(this);
        this.updateRes = this.updateRes.bind(this);
        this.handleDetailChange = this.handleDetailChange.bind(this);
    }

    componentDidMount() {
        this.updateRes();
    }

    getEntries = async () => {
        this.setState({
            loading: true,
        });

        const response = await fetch(
            this.props.location.pathname + this.props.location.search 
        );
        const body = await response.json();

        return body;
    };

    updateRes = async () => {
        this.getEntries()
            .then((resolve) =>
                this.setState({
                    answer: resolve.answer,
                })
            )
            .catch((err) => console.log(err));
    };

    handleInputChange(event) {
        this.setState({
            input: event.target.value,
        });
    }

    render() {
        let currentPath = this.props.location.pathname;
        let qString = querystring.stringify(this.state.input);

        return (
            <div id='result-page'>
                <div>This is the answer : {this.state.answer}</div>

                <label htmlFor='input'>Input here:</label>

                <input type='text' name={'input'} onChange={this.handleInputChange} />

                <Link to={`${currentPath}?${qString}`} onClick={this.updateRes}>
                    <button> Search </button>
                </Link>
            </div>
        );
    }
}

export default SearchResult;

What it does is not what I expected. When i click search, the answer I got was based from the previous page criteria/querystring (not the new one that i just inputted). This is maybe because the onClick of <Link/> is executed before the query string is updated with a new one, which is not what i want! How do I make the OnClick handler executed after the url has been changed and refreshed by link?

Upvotes: 0

Views: 820

Answers (2)

Tarukami
Tarukami

Reputation: 1160

Usually the scheme is like below (spoiler - Routes should be used):

  1. The click on Link changes path.
  2. Route send axios request based on parameteres sent in path and shows "loading.."
  3. When response from server is recieved, the data representing components is to be updated. This will work even if user opens the link "http:\yourapp.com\what-is-the-highest-mountain-in-the-world" without visiting the search page

Upvotes: 1

k-wasilewski
k-wasilewski

Reputation: 4663

That's because in onClick you call an async function. You have to await for it's result, I guess. Try it like this:

onClick={async () => {await this.updateRes();}}

Upvotes: 0

Related Questions