I have a component that opens the dialog to provide inputs:
function App() {
const [toggle, setToggle] = useState(false);
return (
<>
<button onClick={setToggle(true)}>Show Dialog</button>
</>
);
}
export default App;
This is the dialog component which is opened:
function Dialog() {
return (
<>
<span>
<div> Name: </div>
<input type="text" />
</span>
<span>
<div> Select: </div>
<SelectionBox/>
</span>
</>
);
}
export default Dialog;
Selection box component code is as following:
function SelectionBox() {
const [value, setValue] = useState("");
const [options, setOptions] = useState([]);
const apiCalls = () => {
service.getData1().then((data) => {
service.getData2(data).then((opt) => {
setOptions(opt);
}).catch((e1) => {
console.log(e1);
});
}).catch((e) => {
console.log(e);
});
};
return (
<>
<Select
label="select"
options={options}
value={value}
/>
</>
);
}
export default SelectionBox;
Selection box component calls two APIs to get and display the data in selection box. This API call takes time and I want to call the API only once when I open the dialog box and memoize that response for further dialog box actions. This select box can be re-used at some other place also and data is going to be same at all the places. How can I achieve this?
PS: I want to call the APIs when component is mounted. Also, not open to use any libraries.
You can do that with the help of an useEffect and localStorage. On every mount, you check if there is saved data inside localStorage, if yes use it, else you call your api, and store the result inside localStorage. Something like so:
import { useEffect } from "react";
function SelectionBox() {
const [value, setValue] = useState("");
const [options, setOptions] = useState([]);
useEffect(() => {
const apiCalls = () => {
service.getData1().then((data) => {
service
.getData2(data)
.then((opt) => {
localStorage.setItem("options", JSON.stringify(opt));
setOptions(opt);
})
.catch((e1) => {
console.log(e1);
});
})
.catch((e) => {
console.log(e);
});
};
let opt;
try {
opt = JSON.parse(localStorage.getItem("options"));
} catch (error) {
console.log(error)
}
if (!Array.isArray(opt)) {
apiCalls();
} else {
setOptions(opt);
}
}, []);
return (
<>
<Select label="select" options={options} value={value} />
</>
);
}
export default SelectionBox;