简体   繁体   中英

I need to call the page render after POST request

I submit a request to the server and then want to get the result without reloading the page (SPA principle), how can this be done using useEffect()?

I tried to do something like this:
useEffect (() => {
addProduct ();
})

but it's was a bad idea

import React,  {useState, useEffect} from 'react';
import api from './api';

const HandleProduct = () => {
  const [name, setName] = useState('');
  const [description, setDescription] = useState('');

  const updateName = (e) =>{
    setName(e.target.value);
  }
  const updateDescription = (e) =>{
    setDescription(e.target.value);
  }
  const addProduct = () =>{
    const product = {
      name: name,
      description: description
    }
    api.addProduct(product)
    .then((req, res) =>{
      console.log(res);
    })
  }
return (
    <div>
        <form onSubmit={addProduct}>
            <input type="text" name="name" value={name} onChange={updateName}/>
            <input type="text" name="description" value={description} onChange={updateDescription}/>
            <button>Submit</button>
        </form>
    </div>
  );
}
export default HandleProduct;

When the callback with response is called you've got the repsonse with all data sent from API. Let's assume you want to get ID. I will add new hook for storing ID, setting it after POST method is completed, and displaying it.

  const [productId, setProductId] = useState(null);
  const [name, setName] = useState('');
  const [description, setDescription] = useState('');

  const updateName = (e) =>{
    setName(e.target.value);
  }
  const updateDescription = (e) =>{
    setDescription(e.target.value);
  }

    onSubmit() {
        const product = {
          name: name,
          description: description
        }
        api.addProduct(product)
        .then((req, res) =>{
          setProudctId(JSON.parse(res).id);
        })
      }


return (
    <div>

        {productId && <span>Your productId: {productId} </span>} 

        <form onSubmit={addProduct}>
            <input type="text" name="name" value={name} onChange={updateName}/>
            <input type="text" name="description" value={description} onChange={updateDescription}/>
            <button>Submit</button>
        </form>
    </div>
  );
}
export default HandleProduct;

Your code seems legit, yet, given that is not working, I'll give you another option to do it.

In App.js

<Router >
            <ProductsProvider>
              <Route exact path="/products" component={ProductsList} props={...props} />
              <Route exact path={'/products/add'} component={HandleProduct} 
props={...props} />
            </ProductsProvider>
          </Router>

In HandleProduct.js

import React,  {useState} from 'react';
import api from './api';
import { Redirect } from 'react-router'

const HandleProduct = ({history}) => {
  const [name, setName] = useState('');
  const [description, setDescription] = useState('');

  const updateName = (e) =>{
    setName(e.target.value);
  }
  const updateDescription = (e) =>{
    setDescription(e.target.value);
  }
  const addProduct = (e) =>{
    e.preventDefault();
    const product = {
      name: name,
      description: description
    }
    api.addProduct(product)
    .then((req, res) =>{
      history.push('/products');
    })
  }

return (
    <div>
        <form onSubmit={addProduct}>
            <input type="text" name="name" value={name} onChange={updateName}/>
            <input type="text" name="description" value={description} onChange={updateDescription}/>
            <button>Submit</button>
        </form>
    </div>
  );
}
import React, {useContext} from 'react';
import {ProductsContext} from './ProductsContext';

const ProductsList = () => {
  const [data] = useContext(ProductsContext);
  return (
    <div>
      {console.log(data)}
        {data.products.map((product, index)=>(
            <div key={index}>
                <p>{product.name}</p>
                <p><i>{product.description}</i></p>
            </div>
        ))}
    </div>
  );
}
export default ProductsList;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM