Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
274 views
in Technique[技术] by (71.8m points)

react redux - ReactJS - pass parameter to fetch request

Following is the React component displaying all categories, at this route http://localhost:3000/categories

import React, { useEffect, useState } from 'react';
import { useDispatch, useSelector } from "react-redux";
import { Link } from "react-router-dom";
// Material-UI core
import Grid from '@material-ui/core/Grid';
import Container from '@material-ui/core/Container';
// Local Components
import BodyWrapper from 'components/bodyWrapper';
import Spinner from 'components/progressAnimations/spinner';
import CategoryCard from 'components/categoryCard';

import { CARD1, CARD2, CARD3 } from '../../constants'; // images
import { useStyles } from './style';

function Categories(props) {
    const classes = useStyles();
    const loading = useSelector(state => state.categories.isLoading);
    const categories = useSelector(state => state.categories.categories);

    return (
        <BodyWrapper spacing = "40px" containerWidth = "lg">
            <h2>Categories</h2>
            <Grid container spacing={4}>
                {
                    !loading ?
                    categories.data[0].documents.map((category, index) => (
                        <Grid key={index} item xs={6} md={4} lg={3} >
                            <Link to = {`/categories/${category.name}`} style={{ textDecoration: "none" }}>
                            <CategoryCard image={ category.imageUrl || CARD2 } title={ category.name } />
                            </Link>
                        </Grid>
                    )) : (
                        <div className = { classes.spinner }>
                            <Spinner />
                        </div>
                    )
                }
            </Grid>
        </BodyWrapper>
    );
}

export default Categories;

When clicked on a specific category I want load a new component and create a GET request to server with the id of category to load all data related to category.

http://localhost:3000/categories/Photographers

This is the API URL, I want to send "categories id" with the GET request.

{{SERVER}}/api/vendor/getAll?page=1&limit=10&categories=5fdf4d9db1ecf930cd09331b

I want know the best way to pass categories id to next component.

question from:https://stackoverflow.com/questions/65862922/reactjs-pass-parameter-to-fetch-request

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can make it like this:

import React, { useEffect, useState } from "react";
import axios from "axios";

const Categories = (props) => {
  // we get something from Redux
  const categories = ["a", "b", "c", "d", "e", "f"];
  const [currentCategory, setCurrentCategory] = useState(null);

  return props.loading ? (
    "Loading..."
  ) : (
    <div>
      <h2>Select category</h2>
      {categories.map((category) => (
        <div key={category} onClick={() => setCurrentCategory(category)}>
          Category: {category}
        </div>
      ))}
      <div>current category is {String(currentCategory)}</div>
      {currentCategory && <Category id={currentCategory} />}
    </div>
  );
};

const Category = ({ id }) => {
  const [data, setData] = useState(null);

  const url = "https://someurl.com";

  useEffect(() => {
    const fetchData = async () => {
      const dataFromServer = await axios.get(`${url}/${id}`);
      setData(dataFromServer);
    };
    fetchData();
  }, [id]);

  return data ? (
    <div>Render data here: {data}</div>
  ) : (
    `Loading category ${id}...`
  );
};

const App = () => {
  return (
    <div>
      <Categories />
    </div>
  );
};

export default App;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...