more about custom hooks
https://reactjs.org/docs/hooks-custom.html
custom hooks like regular react hooks so you can create your own hooks and make them reusable entities.
one note hook name should start with the use keyword.
working link
https://stackblitz.com/edit/react-wk6ueh
https://reactjs.org/docs/hooks-custom.html
custom hooks like regular react hooks so you can create your own hooks and make them reusable entities.
one note hook name should start with the use keyword.
working link
https://stackblitz.com/edit/react-wk6ueh
import React, { Component,useEffect,useState } from 'react';
import { render } from 'react-dom';
import Hello from './Hello';
import './style.css';
//usefetchData hook uses to fetch data from any api
const usefetchData=(url)=>{
//check status data is loaded or not
const [status,setStatus]=useState(false)
//set data when its loaded sucessfully
const [data,setData]=useState(null);
useEffect(()=>{
const getData=async()=>{
const response=await fetch(url).catch((err)=>{
console.error("Error in fetching")
});
const data=await response.json().catch((err)=>{
console.error("Invaild json type");
});
setData(data);
setStatus(true);
}
getData(url);
},[ ])
return [status,data];
}
//deep copy
const useDeepCopy=(fromObject)=>{
const [deepobject,setdeepobject]=useState({});
const deepCopy=(deepobject,fromObject)=>{
for(const [key,value] of Object.entries(fromObject))
{
if(typeof value==="object")
{
let newObject=new Object();
deepobject[key]=newObject;
deepCopy(newObject,fromObject[key]);
}else
{
deepobject[key]=value;
}
}
}
useEffect(()=>{
deepCopy(deepobject,fromObject);
},[])
return deepobject;
}
const obj={
name:"manish",
age:22,
working:
{
software:"eng",
lang:"c++,javascript"
}
}
//i am dealing with all custom hooks here
const Counter=()=>{
//deep copy of a object and return a newObject
const newObject=useDeepCopy(obj)
//fetch data from api
const [status,data]=usefetchData('https://jsonplaceholder.typicode.com/todos/1');
//deep copy custom hook
useEffect(()=>{
obj.name="ranjeet";
obj.working=null;
console.log("real",obj);
console.log("copy",newObject)
},[newObject])
return <div>
<div>
{
//fetch json custom hook
(!status)?"loading...":"user id=>"+ data.userId+" "+"user data is=>"+data.title
}</div>
</div>
}
class App extends Component {
constructor() {
super();
this.state = {
name: 'React'
};
}
render() {
return (
<div>
<Hello name={this.state.name} />
<Counter/>
</div>
);
}
}
render(<App />, document.getElementById('root'));
Comments
Post a Comment