Home > Blockchain >  React State not changing after Axios request
React State not changing after Axios request

Time:06-24

I'm currently trying to build a search with an API request to my backend. So far that is working but my state for the loading icon is not fully going back to it's "false" state after the results are showing. I'm also not getting any errors. I logged the state and it indicates that false is set for loading after the results are showing, but my code on line 81-91 doesn't seem to update my loading element accordingly.

import { useContext ,useState } from 'react';
import { AuthContext } from "../contexts/AuthContext"
import {
  Button,
  Form,
  Input,
  Spin
} from 'antd';
import axios from 'axios';
import Results from '../containers/Results';
import { API } from "../api"
const formItemLayout = {
  labelCol: {
    span: 6,
  },
  wrapperCol: {
    span: 14,
  },
};

const Searches = () => {

  const [loading, setLoading] = useState(false)
  const [results, setResults] = useState([])


  const { accessToken } = useContext(AuthContext);

  const onFinish = (values) => {
    const Name =
      values["input-numbersearches"] === undefined ? null : values["input-numbersearches"];
    
    setLoading('true');

    axios.get(API.facilities.search, {
      headers: {
        "Authorization": `Bearer ${accessToken}`
      },
      withCredentials: true,
      params: {
        Name
      }
    })
    .then(res => {
      setResults(res.data);      
      setLoading('false');
    })
    .catch(err => {
      console.log(err);
    });
  };


  return (
    <div>
      <h1 className="">Claim Facilities</h1>
      <p></p>
      <Form
        name="validate_other"
        {...formItemLayout}
        onFinish={onFinish}
        initialValues={{
        }}
      >



          <Form.Item name="input-numbersearches" noStyle>
            <Input
              name="searchfields"
              placeholder="enter facility name"
              // onSubmit={value => console.log(value)}
              style={{ width: 200 }}
            />          
  
          </Form.Item>
          <Button type="primary" htmlType="submit">
            Search
            </Button>
        {results ? ( 
          <Results facilities={results} />
        ) : (
          <h1>No results</h1>
        )}
        {loading ? ( <div className='loading'>
          <Spin />
        </div>
        ) : (
          <Results facilities={results} />
        )}
        <Form.Item
          wrapperCol={{
            span: 12,
            offset: 6,
          }}
        >
        </Form.Item>
      </Form>
    </div>
    
  );
};

export default Searches;

I initially tried it this way which makes more sense to me but it resulted in the results now showing but instead i got the loading icon endlessly:

        {loading ? ( <div className='loading'>
          <Spin />
        </div>
        ) : (
          <Results facilities={results} />
        )}

CodePudding user response:

You are setting setLoading('false'); which is a string and non-empty string is coerced to true in statements. You should set a boolean rather than string setLoading(false);

CodePudding user response:

whatever you set loading to 'true' or 'false', both of their type is string rather than boolean, so you'd better to use true and false. By the way, the reason why you set 'true' can work successful is that the string 'true' will be convert to true which is boolean type and the string 'false' is same as 'true'.

  • Related