AkForDev
AkForDev

Reputation: 389

How to reload api fetch call on variable change in React js?

I'm creating a block for Wordpress with Gutenberg Editor, which is working on React js.

So I'm calling Wordpress API by apiFetch(), which is same to fetch():

class PortfolioTagsEdit extends Component {
    constructor(props) {
        super(props);
        this.state = {
          data: [],
          isLoading: false,
        };
    }
    componentDidMount() {
        const { attributes } = this.props;
        const { switcher } = attributes;
        this.setState({ isLoading: true });
        apiFetch( { path: `/wp/v2/${switcher}?post` } )
          .then(data => this.setState({ data, isLoading: false }));
    }
 
  ...
}

For variable switcher I have controllers which are changing the value.

My problem is when I switch the value of switcher I should reload api call, but I don't know how)

Can you help me, please?

Upvotes: 0

Views: 1643

Answers (2)

Jibin Thomas
Jibin Thomas

Reputation: 864

Using react hooks you can use useEffect for fetching API.

function PortfolioTagsEdit({ attributes }) {
    // state
    const [loading, setLoading] = useState(false);
    const [data, setData] = useState([])

    // here useEffect will run on component mount and every-time attributes.switcher changes
    useEffect(() => {
        setLoading(true)
        apiFetch( { path: `/wp/v2/${switcher}?post` } )
          .then(data => {
              setLoading(false)
              setData(data)
          });
    }, [attributes.switcher]) 


    return (
     ....
    )
}

Upvotes: 4

Pedro Filipe
Pedro Filipe

Reputation: 1075

The easiest way to do this would be to have the switcher variable in state. You can then implement the componentDidUpdate method to call your apiFetch:

class PortfolioTagsEdit extends Component {
    constructor(props) {
        super(props);
        this.state = {
          data: [],
          isLoading: false,
          switcher: this.props.attributes.switcher
        };
    }

    componentDidMount() {
        this.callAPI()
    }

    componentDidUpdate(prevProps, prevState) {
       if (prevState.switcher !== this.state.switcher) this.callAPI();
    }
    
    callAPI() {
        const { switcher } = this.state;

        this.setState({ isLoading: true });

        apiFetch( { path: `/wp/v2/${switcher}?post` } )
          .then(data => this.setState({ data, isLoading: false }));
    }
    ...
}

Check out the docs for componentDidUpdate - https://reactjs.org/docs/react-component.html#componentdidupdate

You could also take a look on how to do this using hooks, specifically useEffect -https://reactjs.org/docs/hooks-reference.html#useeffect

Upvotes: 1

Related Questions