In componentDidMount() I'm calling setQueryParams to set the query parameters into state which works fine.
componentDidMount() {
this.setQueryParams();
console.log(this.state.query);
$.getJSON(`/search?${this.state.query}`, (response) => {
this.addDiveCenters(response.centers)
this.buildFilters(response.filters, false)
});
console.log(this.state.query);
}
However, after the setQueryParams()
call, console.log(this.state.query)
is returning '' (the default state). After the page loads I can run $r.state.query and everything is perfect,but for some reason I cannot access the state! I need the initial state to make an AJAX call. Right now, every single page loads to /search
because this.state.query
is blank.
setQueryParams = (param = null, value = null) => {
const query = this.state.query;
// get current location
const location = this.props.location.search;
// Set params based on whether component mount or filter change
const params = param ? new URLSearchParams(query) : new URLSearchParams(location);
if (param) {
params.set(param, value);
}
this.setState({
query: params.toString()
});
console.log(this.state.query); // doesn't display anything!
}