skip to Main Content

my component

 

import React from "react";
//import HeadingRow from './HeadingRow';
import { useState, useEffect } from "react";
import Results from './Results';
 import {useRoutes,
  useParams, Outlet, useLocation, useNavigate } from "react-router-dom";
          
import Card from './Card';



class Services extends React.Component {
         

          constructor(props) {
            super(props);
            console.log(props);
            this. state = {
            cards: [],
            cardsError: "",
            id: props.id
          };
            
          }
        fetchServices = async (id) => {
            const res = await fetch(`http://localhost:5000/cards/${id}`);
            const data = await res.json();

            return data;
          };
        fetchgetServiceseses = async () => {
            const res = await fetch(`http://localhost:5000/cards`);
            const data = await res.json();
            console.log(data);
            return data;
          };
 

        async componentDidMount() {

            const {id} = this.state;
                
                if(id){

                    const data_card = await this.fetchServices(id);
                    const cards = [data_card] ;
                    this.setState({cards });
                    console.log(id);
                    console.log(cards);

                }else{

                        const cards = await this.fetchgetServiceseses();
                  this.setState({ cards });
                }

        }
        async componentDidUpdate() {

                const {id} = this.state;
                    
                    console.log(id);
                     
                    /*
                if(id){

                    const data_card = await this.fetchServices(id);
                    const cards = [data_card] ;
                    this.setState({cards });
                    console.log(id);
                    console.log(cards);

                }else{

                        const cards = await this.fetchgetServiceseses();
                  this.setState({ cards });
                }
                */
        }

        render() {  

             /*const forms_result =  this.setFormsResults();
              console.log(forms_result);*/
             const { cards } = this.state;
                console.log(cards);
                    console.log(cards.length);
            return (<div className="container px-4 px-lg-5 my-5">
                  
                 
             {cards.length > 0 ? (
                <div className="row gx-4 gx-lg-5   ">
                    {cards.map((card, key) => <Card name={card.name}  id={card.id} key1={key} key={key}  link={card.link} sort={card.sort} text={card.text} linkAlias={card.linkAlias} />)}
                </div>
              ) : (
                "Emry results"
              )}

              <Outlet />

            </div>);
             };

    };


export default Services;  
export const ServicesFunk = props => {
  const {id} = useParams();
  console.log(id);
const location = useLocation();
  const navigate = useNavigate();

  const [state] = useState(location.state || {});  

  useEffect(() => {
    navigate(".", { replace: true });  
  }, [navigate]);

  `return <Services id={id} navigate={navigate} {...props} />;`


}  

my app use route

const App = () => (
    
          <Routes>
            


               <Route
                path="/"
                exact 
                element={    <>
                     <TopMenuBlock />
                   <PageContent />
                   <Footer />
                    </>   }
              /> 
              <Route
              path="/form-result"
              exact
               element={    <>
                 <TopMenuBlock /> 
                 <FormResults />
                  <Footer />
                </>   }
            /> 
            <Route
              path="/about/"
              exact
               element={    <>
                 <TopMenuBlock /> 
                 <About />
                  <Footer />
                </>   }
            /> 
            
            <Route
              path="/contact/"
              exact
               element={    <>
                 <TopMenuBlock /> 
                 <Contact />
                  <Footer />
                </>   }
            /> 
            <Route
              path="/services/:id?"
              
               element={    <>
                  <TopMenuBlock /> 
                
                  <ServicesFunk />
                  <Footer />
                </>   }
            > 
           
          </Route>


      </Routes>
   
);

export default App;

when I go to pages

http://localhost:3000/services/1/ и http://localhost:3000/services/2/
the page remains the same, kod

return <Services id={id} navigate={navigate} {...props} />;
does not give a result and is not called. I get the answer here

const {id} = useParams(); console.log(id);

but not here
`async componentDidUpdate() {

            const {id} = this.state;
                
                console.log(id);`

id – undefined

I tried to find an answer on stackoverflow and other sites, no result

2

Answers


  1. As per your code, <Services…> seems to be in backticks. Remove that and try

    Login or Signup to reply.
  2. In your ServicesFunk component, you’re correctly using useParams() to get the id from the URL, but you’re passing it to the Services component as a prop. However, since Services is a class component, it relies on lifecycle methods like componentDidMount and componentDidUpdate. The problem arises because the componentDidUpdate method is not being called as expected, leading to the id in your state remaining undefined.

    Move the ID Handling to componentDidUpdate: Ensure that componentDidUpdate checks for changes in the id prop and updates the state accordingly.
    Simplify the Setup: Consider refactoring the component into a functional component to make use of hooks like useEffect, which simplifies handling updates when props change.

    this is your services component

        import React, { useState, useEffect } from "react";
    import { useParams, Outlet } from "react-router-dom";
    import Card from './Card';
    
    const Services = (props) => {
      const { id } = useParams();
      const [cards, setCards] = useState([]);
      const [cardsError, setCardsError] = useState("");
    
      const fetchServices = async (id) => {
        try {
          const res = await fetch(`http://localhost:5000/cards/${id}`);
          const data = await res.json();
          return data;
        } catch (error) {
          setCardsError("Failed to fetch card");
        }
      };
    
      const fetchAllServices = async () => {
        try {
          const res = await fetch(`http://localhost:5000/cards`);
          const data = await res.json();
          return data;
        } catch (error) {
          setCardsError("Failed to fetch cards");
        }
      };
    
      useEffect(() => {
        const fetchData = async () => {
          if (id) {
            const data_card = await fetchServices(id);
            setCards([data_card]);
          } else {
            const allCards = await fetchAllServices();
            setCards(allCards);
          }
        };
    
        fetchData();
      }, [id]); // Dependency array includes 'id' to re-fetch when it changes
    
      return (
        <div className="container px-4 px-lg-5 my-5">
          {cards.length > 0 ? (
            <div className="row gx-4 gx-lg-5">
              {cards.map((card, key) => (
                <Card
                  name={card.name}
                  id={card.id}
                  key1={key}
                  key={key}
                  link={card.link}
                  sort={card.sort}
                  text={card.text}
                  linkAlias={card.linkAlias}
                />
              ))}
            </div>
          ) : (
            "Empty results"
          )}
          <Outlet />
        </div>
      );
    };
    
    export default Services;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search