I’m a novice in react and I’m trying to use a variable from one page in another.
Here is the code the an currently working with:
TilbudSide.js:
import React, { useState, useEffect } from 'react';
import StartSide from './StartSide';
function TilbudSide () {
const [selectedCustomer, setSelectedCustomer] = useState(null);
const [selectedCustomerNumber, setSelectedCustomerNumber] = useState(null);
let apiUrlCostumers = null;
const selectedCompany = StartSide().selectedCompany; // Access selectedCompany from StartSide
console.log('SELECTEDCOMPANY '+ selectedCompany );
if (selectedCompany === 'NOA') {
apiUrlCostumers = 'http://localhost:8000/customers';
};
console.log(apiUrlCostumers)
return (
<div className="tilbud-side">
<h2>Lag tilbud</h2>
</div>
);
export default TilbudSide;
StartSide.js
import { useState } from "react";
import { useNavigate } from "react-router-dom";
import logo from './assets/NA_logo.svg';
import './StartSide.css';
function StartSide() {
const [selectedCompany, setSelectedCompany] = useState('');
const navigate = useNavigate()
const handleClickNOA = () => {
setSelectedCompany('NOA');
navigate('/tilbudside');
// Perform any additional logic or actions upon clicking the icon
};
console.log(selectedCompany);
return (
<div onClick={handleClickNOA} style={{ cursor: 'pointer' }}>
<img src={logo} className="NA-logo" alt="NA Logo" />
</div>
);
}
export default StartSide;
Everytime try to run TilbudSide.js the console log for apiUrlCostumers is always null and selectedCompany is always null. I dont understand why selectedCostumer doesn’t change in StartSide.js handleClickNOA(). Please help me.
2
Answers
Your attempt to retrieve the selectedCompany variable from StartSide in the TilbudSide component is where the problem in your code lies. Right now, you are attempting to directly access the state of StartSide as a component. You should consider creating a different method that returns the chosen business value, though.
You can change your code in the following way to fix this:
TilbudSide.js:
startside.js:
By exporting StartSide as a function and calling it to retrieve the selectedCompany value, you can access it correctly in the TilbudSide component.
What I would suggest is to change a little bit the state handling, because I think there are easier approaches and cleaner.
You can use following approaches to handle state in your app:
useMemo
anduseCallback
. Still – let’s you to share the state between components and pass it deeply (learn aboutprops drilling
)