Reload component with react hooks - reactjs

I would like to ask you how to reload a component after modifying the data of a form, then I have my component:
export default function MyComponent() {
const url = "/api/1";
const [resData, setResData] = useState(null);
useEffect(() => {
const jwt = getJwt();
const fetchData = async () => {
const resP = await axios(url);
setResData(resP.data);
};
fetchData();
}, []);
return <EditComponent={resData} />
}
This component passes my data to the "EditCompoent" child component in which there is a form that is filled with data from the parent component that I can modify in which there is a save button that when I click allows me to send the modified data to my beckend:
const handleConfirm = () => {
axios.put(url, data).then((res) => {
//Reload Component
})
}
I would like to be able to reload the parent component as soon as this works is successful what could I do? I don't want to reload the whole page I just want to reload the parent component that is "MyComponent", I hope I have well posed the problem.

I'd pass the whole useEffect callback down so that handleConfirm can call it again after the axios.put, after which the resData state in the parent will be updated:
export default function MyComponent() {
const url = "/api/1";
const [resData, setResData] = useState(null);
const tryLoginJWT = () => {
const jwt = getJwt();
const resP = await axios(url);
setResData(resP.data);
};
useEffect(tryLoginJWT, []);
return <EditComponent {...{ resData, tryLoginJWT }} />
}
const handleConfirm = () => {
axios.put(url, data)
.then(tryLoginJWT)
.catch(handleErrors); // don't forget to catch here in case there's a problem
}

Related

How to automatically refresh getstream.io FlatFeed after a new post using reactjs?

I would like to understand how can I auto-update the feed after submitting the form through the StatusUpdateForm component. At the moment I have to refresh the page to see the changes.
In general, my task is to differentiate feeds based on the user's location, I requested extended permissions from support so that different users can post to one feed, and therefore I use the modified doFeedRequest parameters of the FlatFeed component to show the feed without being tied to the current user and it works.
I do not use notification, I want the posted messages to appear immediately in the feed.
If I wrote my own custom feed (FeedCustom) component to display data, it would work fine, but how do I make it work with FlatFeed of getstream.io? Any help would be greatly appreciated.
import React, { useEffect, useState } from 'react';
import { StreamApp, FlatFeed, StatusUpdateForm } from 'react-activity-feed';
import 'react-activity-feed/dist/index.css';
// import FeedCustom from './FeedCustom';
const STREAM_API_KEY = 'XXXXXXXXXXXXXXXX';
const STREAM_APP_ID = 'XXXXX';
const App = () => {
const [userToken, setUserToken] = useState(null);
const [loading, setLoading] = useState(true);
const [locationId, setLocationId] = useState(null);
const [data, setData] = useState([]);
const callApi = async () => {
const response = await fetch('https://localhost:8080/user-token')
const userResponse = await response.json();
return userResponse;
};
useEffect(() => {
callApi()
.then(response => {
const resp = JSON.parse(response.body);
setLoading(false);
setUserToken(resp.userToken);
setLocationId(resp.locationId);
})
.catch(e => alert(e));
}, []);
const customDoFeedRequest = (client, feedGroup = 'timeline', userId = locationId, options) => {
const feed = client.feed(feedGroup, userId);
const feedPromise = feed.get(options);
feedPromise.then((res) => {
setData((data) => res.results);
});
return feedPromise;
}
return loading ? (
<div>.... Loading ....</div>
) : (
<StreamApp
apiKey={STREAM_API_KEY}
appId={STREAM_APP_ID}
token={userToken}
>
{/* <FeedCustom dataFeed={ data } /> */}
<FlatFeed doFeedRequest={customDoFeedRequest} />
<StatusUpdateForm
userId={locationId}
feedGroup={'timeline'}
onSuccess={(post) => setData((data) => [...data, post])}
/>
</StreamApp>
)
};
export default App;
My backend https://localhost:8080/user-token returns an object kind of:
{
userToken: 'XXXXXXX'
locationId: 'XXXXXXX'
}

(React JS Hooks issue) React JS only render posts from logged in user

Problem
I am new to React and am trying to build an application whereby logged in users can view posts they have created. I am having issues with asynchronous functions causing variables to be accessed before they are loaded in. I am using a Firestore database.
Code
I followed this tutorial to set up authentication. I have created an AuthContext.js file, which contains this code (reduced):
const AuthContext = createContext();
export const AuthContextProvider = ({children}) => {
const [user, setUser] = useState({});
// const googleSignIn = () => {...}
// const logOut = () => {...}
useEffect(() => {
const unsubscribe = onAuthStateChanged(auth, (currentUser) => {
setUser(currentUser);
});
return () => {
unsubscribe();
}
}, []);
return (
<AuthContext.Provider value={{ googleSignIn, logOut, user }}>
{children}
</AuthContext.Provider>
)
};
export const UserAuth = () => {
return useContext(AuthContext);
}
I then wrap my application with a AuthContextProvider component and import UserAuth into any component that I want to be able to access the user object from. I have a PostPage component, and in it I want to ONLY render posts created by the logged in user. Each post has a user property containing the uid of the author. Here is my code:
import { UserAuth } from './context/AuthContext'
const PostsPage = () => {
const { user } = UserAuth();
const [posts, setPosts] = useState([]);
const postsRef = collection(db, 'posts');
useEffect(() => {
const getData = async () => {
if (user) {
const q = query(postsRef, where('user', '==', user.uid));
const data = await getDocs(q);
const filtered = data.docs.map((doc) => ({ ...doc.data(), id: doc.id }));
setPosts(filtered);
}
}
return () => {
getData();
}
}, [user]);
return (
// Display posts
)
}
export default PostsPage;
Upon immediately refreshing the page, getData is executed. However, the code wrapped in the if statement does not run because the user has not yet been loaded in. Yet despite the dependancy array, getData is not executed again once the user data loads in, and I can't figure out why. If I render the user's uid, e.g. <p>{ user.uid }</p>, it will soon appear on the screen after the data has been loaded. But, I cannot figure out how to trigger getData after the user has been loaded. Any help with this would be much appreciated, thanks.
You have an issue just because you put getData() call to the cleanup function of a hook. Cleanup function will execute on depsArray change but it will be executed with old data, closure captured. So when user changes from undefined => any - getUser will be called and will still have a closure-captured user set to undefined. You can clear the array instead in it, so if user logs out - dont show any messages
useEffect(() => {
const getData = async () => {
if (!user) return;
const q = query(postsRef, where("user", "==", user.uid));
const data = await getDocs(q);
const filtered = data.docs.map((doc) => ({
...doc.data(),
id: doc.id
}));
setPosts(filtered);
};
getData().catch(console.error);
return () => {
setPosts([]);
};
}, [user]);

how to fetch data from webservice in REACT useEffect function and send it to props object?

I'm trying to fetch data from a webservice to a child component. It looks like Data are fetched ok in console.log() inside useEffect function. I'm not able to work with them in higher function scope. I'd like to access fetched data in the child component (PComponent) through the props object.
Thank you for any advice.
function App(props) {
let data = undefined;
useEffect( () => {
console.log('UseEffect');
const fetchData = async () => {
const result = await axios.get(someUrl)
data = result.data;
console.log('result',data);
return data;
};
data = fetchData();
}, []);
return (
<PComponent settings = {data}/>
);
}
export default App;
Try useState hook to store your data. Any state update will rerender the component and therefore data is passed to the child.
const App = (props) => {
const [data, setData] = React.useState()
const fetchData = async() => {
const result = await axios.get(someUrl)
setData(result);
};
// Fetch data when component mounted
useEffect( () => {
fetchData()
}, []);
return (
<PComponent settings={data}/>
);
}
export default App;
You have to use useState for state which can change in functional components. You can read about that on the React docs.
function App(props) {
const [data, setData] = useState(undefined);
useEffect(async () => {
console.log("useEffect running");
const fetchData = async () => {
const result = await axios.get(someUrl);
console.log(result.data);
return result.data;
};
setData(await fetchData());
}, []);
return <PComponent settings={data} />;
}

When params or queries chnage the component does not update

I'm using react-router-dom v5, and react 16
Whenever I navigate like this:
from "/products/:someId" to "/products/:someOtherId"
the url changes but the components do not update accordingly
it's the same with queries.
"/products?search=something" or "/products?search=someOtherThing"
it does work when I'm in a different url, like "/" or "/users",
I'm using Link for navigation, I also tried the useHistory hook: history.push, history.replace and withRouter(myComponent);
This is how I'm getting data from queries/params
async function searchProducts(searchValue) {
const response = await axios.post(
"http://localhost:8000/api/products/search",
{ search: searchValue });
return response.data.body;
}
const useFetchData = (query) => {
const [products, setProducts] = useState([]);
useEffect(() => {
if (products.length === 0) {
// Use searchProducts for the request
searchProducts(query).then((foundProducts) => {
setProducts(foundProducts);
});
}
}, [products, query]);
return products;
};
then I useFetchData in my component which goes:
const ProductList = () => {
const history = useHistory();
// parsing query to be -> { search: "value" }
const urlQuery = queryString.parse(history.location.search);
const products = useFetchData(urlQuery.search);
const getList = () => {
return products.map((product) => {
return (
<li key={product._id}>
<ProductItem product={product} />
</li>
);
});
};
return <div className="container">{getList()}</div>;
};
The search button is in a different component for the header, it's always there since it's in the layout
<button className="header-search-button" onClick={handleClick}>
Search
</button>
and the handleClick:
// searchvalue has it's own onChange handler
const [searchValue, setSearchValue] = useState("");
// code...
const handleClick = () => {
// .... some code
// I also tried with push and Link
history.replace(`/products?search=${searchValue}`);
};
It's really difficult to tell without the code.
But my guess is you are able to change the /products?search=bag to /products?search=watch.
But after that it's not able to update the state and hence no re render.When you reload then the render happens.
It would be easier if we could see the code.

How to send request on click React Hooks way?

How to send http request on button click with react hooks? Or, for that matter, how to do any side effect on button click?
What i see so far is to have something "indirect" like:
export default = () => {
const [sendRequest, setSendRequest] = useState(false);
useEffect(() => {
if(sendRequest){
//send the request
setSendRequest(false);
}
},
[sendRequest]);
return (
<input type="button" disabled={sendRequest} onClick={() => setSendRequest(true)}
);
}
Is that the proper way or is there some other pattern?
export default () => {
const [isSending, setIsSending] = useState(false)
const sendRequest = useCallback(async () => {
// don't send again while we are sending
if (isSending) return
// update state
setIsSending(true)
// send the actual request
await API.sendRequest()
// once the request is sent, update state again
setIsSending(false)
}, [isSending]) // update the callback if the state changes
return (
<input type="button" disabled={isSending} onClick={sendRequest} />
)
}
this is what it would boil down to when you want to send a request on click and disabling the button while it is sending
update:
#tkd_aj pointed out that this might give a warning: "Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function."
Effectively, what happens is that the request is still processing, while in the meantime your component unmounts. It then tries to setIsSending (a setState) on an unmounted component.
export default () => {
const [isSending, setIsSending] = useState(false)
const isMounted = useRef(true)
// set isMounted to false when we unmount the component
useEffect(() => {
return () => {
isMounted.current = false
}
}, [])
const sendRequest = useCallback(async () => {
// don't send again while we are sending
if (isSending) return
// update state
setIsSending(true)
// send the actual request
await API.sendRequest()
// once the request is sent, update state again
if (isMounted.current) // only update if we are still mounted
setIsSending(false)
}, [isSending]) // update the callback if the state changes
return (
<input type="button" disabled={isSending} onClick={sendRequest} />
)
}
You don't need an effect to send a request on button click, instead what you need is just a handler method which you can optimise using useCallback method
const App = (props) => {
//define you app state here
const fetchRequest = useCallback(() => {
// Api request here
}, [add dependent variables here]);
return (
<input type="button" disabled={sendRequest} onClick={fetchRequest}
);
}
Tracking request using variable with useEffect is not a correct pattern because you may set state to call api using useEffect, but an additional render due to some other change will cause the request to go in a loop
In functional programming, any async function should be considered as a side effect.
When dealing with side effects you need to separate the logic of starting the side effect and the logic of the result of that side effect (similar to redux saga).
Basically, the button responsibility is only triggering the side effect, and the side effect responsibility is to update the dom.
Also since react is dealing with components you need to make sure your component still mounted before any setState or after every await this depends on your own preferences.
to solve this issue we can create a custom hook useIsMounted this hook will make it easy for us to check if the component is still mounted
/**
* check if the component still mounted
*/
export const useIsMounted = () => {
const mountedRef = useRef(false);
const isMounted = useCallback(() => mountedRef.current, []);
useEffect(() => {
mountedRef.current = true;
return () => {
mountedRef.current = false;
};
});
return isMounted;
};
Then your code should look like this
export const MyComponent = ()=> {
const isMounted = useIsMounted();
const [isDoMyAsyncThing, setIsDoMyAsyncThing] = useState(false);
// do my async thing
const doMyAsyncThing = useCallback(async () => {
// do my stuff
},[])
/**
* do my async thing effect
*/
useEffect(() => {
if (isDoMyAsyncThing) {
const effect = async () => {
await doMyAsyncThing();
if (!isMounted()) return;
setIsDoMyAsyncThing(false);
};
effect();
}
}, [isDoMyAsyncThing, isMounted, doMyAsyncThing]);
return (
<div>
<button disabled={isDoMyAsyncThing} onClick={()=> setIsDoMyAsyncThing(true)}>
Do My Thing {isDoMyAsyncThing && "Loading..."}
</button>;
</div>
)
}
Note: It's always better to separate the logic of your side effect from the logic that triggers the effect (the useEffect)
UPDATE:
Instead of all the above complexity just use useAsync and useAsyncFn from the react-use library, It's much cleaner and straightforward.
Example:
import {useAsyncFn} from 'react-use';
const Demo = ({url}) => {
const [state, doFetch] = useAsyncFn(async () => {
const response = await fetch(url);
const result = await response.text();
return result
}, [url]);
return (
<div>
{state.loading
? <div>Loading...</div>
: state.error
? <div>Error: {state.error.message}</div>
: <div>Value: {state.value}</div>
}
<button onClick={() => doFetch()}>Start loading</button>
</div>
);
};
You can fetch data as an effect of some state changing like you have done in your question, but you can also get the data directly in the click handler like you are used to in a class component.
Example
const { useState } = React;
function getData() {
return new Promise(resolve => setTimeout(() => resolve(Math.random()), 1000))
}
function App() {
const [data, setData] = useState(0)
function onClick() {
getData().then(setData)
}
return (
<div>
<button onClick={onClick}>Get data</button>
<div>{data}</div>
</div>
);
}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://unpkg.com/react#16/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom#16/umd/react-dom.development.js" crossorigin></script>
<div id="root"></div>
You can define the boolean in the state as you did and once you trigger the request set it to true and when you receive the response set it back to false:
const [requestSent, setRequestSent] = useState(false);
const sendRequest = () => {
setRequestSent(true);
fetch().then(() => setRequestSent(false));
};
Working example
You can create a custom hook useApi and return a function execute which when called will invoke the api (typically through some onClick).
useApi hook:
export type ApiMethod = "GET" | "POST";
export type ApiState = "idle" | "loading" | "done";
const fetcher = async (
url: string,
method: ApiMethod,
payload?: string
): Promise<any> => {
const requestHeaders = new Headers();
requestHeaders.set("Content-Type", "application/json");
console.log("fetching data...");
const res = await fetch(url, {
body: payload ? JSON.stringify(payload) : undefined,
headers: requestHeaders,
method,
});
const resobj = await res.json();
return resobj;
};
export function useApi(
url: string,
method: ApiMethod,
payload?: any
): {
apiState: ApiState;
data: unknown;
execute: () => void;
} {
const [apiState, setApiState] = useState<ApiState>("idle");
const [data, setData] = useState<unknown>(null);
const [toCallApi, setApiExecution] = useState(false);
const execute = () => {
console.log("executing now");
setApiExecution(true);
};
const fetchApi = useCallback(() => {
console.log("fetchApi called");
fetcher(url, method, payload)
.then((res) => {
const data = res.data;
setData({ ...data });
return;
})
.catch((e: Error) => {
setData(null);
console.log(e.message);
})
.finally(() => {
setApiState("done");
});
}, [method, payload, url]);
// call api
useEffect(() => {
if (toCallApi && apiState === "idle") {
console.log("calling api");
setApiState("loading");
fetchApi();
}
}, [apiState, fetchApi, toCallApi]);
return {
apiState,
data,
execute,
};
}
using useApi in some component:
const SomeComponent = () =>{
const { apiState, data, execute } = useApi(
"api/url",
"POST",
{
foo: "bar",
}
);
}
if (apiState == "done") {
console.log("execution complete",data);
}
return (
<button
onClick={() => {
execute();
}}>
Click me
</button>
);
For this you can use callback hook in ReactJS and it is the best option for this purpose as useEffect is not a correct pattern because may be you set state to make an api call using useEffect, but an additional render due to some other change will cause the request to go in a loop.
<const Component= (props) => {
//define you app state here
const getRequest = useCallback(() => {
// Api request here
}, [dependency]);
return (
<input type="button" disabled={sendRequest} onClick={getRequest}
);
}
My answer is simple, while using the useState hook the javascript doesn't enable you to pass the value if you set the state as false. It accepts the value when it is set to true. So you have to define a function with if condition if you use false in the usestate

Resources