Alert Automatic Disappear function - reactjs

My aim is to give the user to see the alert at starting of the my page without clicking any button.And after a while it should be disappear automatically i am trying this on reactjs so any body help me out to find which logic should i apply

First render your alert component. Define a boolean state variable with initial value false.
then update that state variable with setTimeout.
import React, { useState, useEffect } from "react";
export const Alert = () => {
const [timeIsUp, setTimeIsUp] = useState(false);
useEffect(() => {
setTimeout(() => {
setTimeIsUp(true);
}, 5000);
}, []);
if (timeIsUp) {
return null;
}
return <div>your actual alert component content</div>;
};

You can refer this link: custom-modal-popup-component
Also just make the state of modal true at fist and add a setTimeout in useEffect and make it to false after a desired time.

Are you using class components or functional components for rendering your React page?
What you're looking for is called life cycles, i highly recomend you taking a look in ReactJS life cycle docs.
The life cycle method that executes or do something when the page is loaded has two usages:
If you're using class components, there is a native method you can call inside your component called ComponentDidMount(), his usage is available in docs here.
Now, if you're using functional components, you need to take a look on useEffect in React Hooks.
After that, you can take a look in setTimeout native method from javascript as observed.
Hope this helps too!

Related

How to implement promise when updating a state in functional React (when using useState hooks)

I know similar questions are bouncing around the web for quite some time but I still struggle to find a decision for my case.
Now I use functional React with hooks. What I need in this case is to set a state and AFTER the state was set THEN to start the next block of code, maybe like React with classes works:
this.setState({
someStateFlag: true
}, () => { // then:
this.someMethod(); // start this method AFTER someStateFlag was updated
});
Here I have created a playground sandbox that demonstrates the issue:
https://codesandbox.io/s/alertdialog-demo-material-ui-forked-6zss6q?file=/demo.tsx
Please push the button to get the confirmation dialog opened. Then confirm with "YES!" and notice the lag. This lag occurs because the loading data method starts before the close dialog flag in state was updated.
const fireTask = () => {
setOpen(false); // async
setResult(fetchHugeData()); // starts immediately
};
What I need to achieve is maybe something like using a promise:
const fireTask = () => {
setOpen(false).then(() => {
setResult(fetchHugeData());
});
};
Because the order in my case is important. I need to have dialog closed first (to avoid the lag) and then get the method fired.
And by the way, what would be your approach to implement a loading effect with MUI Backdrop and CircularProgress in this app?
The this.setState callback alternative for React hooks is basically the useEffect hook.
It is a "built-in" React hook which accepts a callback as it's first parameter and then runs it every time the value of any of it's dependencies changes.
The second argument for the hook is the array of dependencies.
Example:
import { useEffect } from 'react';
const fireTask = () => {
setOpen(false);
};
useEffect(() => {
if (open) {
return;
}
setResult(fetchHugeData());
}, [open]);
In other words, setResult would run every time the value of open changes,
and only after it has finished changing and a render has occurred.
We use a simple if statement to allow our code to run only when open is false.
Check the documentation for more info.
Here is how I managed to resolve the problem with additional dependency in state:
https://codesandbox.io/s/alertdialog-demo-material-ui-forked-gevciu?file=/demo.tsx
Thanks to all that helped.

which function is called when screen is returned from other screen in react native?

I can see the React native component life cycle. componentDidMount, UNSAFE_componentWillMount, etc
I thought UNSAFE_componentWillMount is called when screen is resumed. But it is not called.
I use React 17 over, React Native 0.68.1, and I use navigation.goBack() to return from second screen to first screen.
Which function is called when screen is resumed? Or what other way to do that?
You need to be careful here. In react-native a screen remains mounted on navigation. This differs from the web.
If you are coming to react-navigation from a web background, you may assume that when user navigates from route A to route B, A will unmount (its componentWillUnmount is called) and A will mount again when user comes back to it. While these React lifecycle methods are still valid and are used in react-navigation, their usage differs from the web.
Hence, if you navigate via goBack, the componentWillMount will not be called again, since the screen remains mounted. There is a general workaround for this problem which is documented here in the React Navigation lifecycle events section.
For functional components, we can use the useFocusEffect hook as follows.
useFocusEffect(
React.useCallback(() => {
// Do something when the screen is focused
return () => {
// Do something when the screen is unfocused
// Useful for cleanup functions
};
}, [])
);
For class components, we can use a focus listener. This is documented here.
class SomeClassComponent extends React.Component {
componentDidMount() {
this._unsubscribe = navigation.addListener('focus', () => {
// do whatever
});
}
componentWillUnmount() {
this._unsubscribe();
}
...
In some cases it might be more convenient to still use functional components. We can simply wrap a legacy class component into a functional component as follows.
const Wrapper = () => {
// useFocusEffect from above.
return <SomeClassComponent />
}
In react native when you change screen and come back to the previous screen it doesn't rerenders so using useEffect hook doesen't work. However you can use useFocusEffect hook provided by the react navigation. You can read more in details Here

React init carousel jQuery lib with useEffect

I'm working on a project on which I have to switch a classic website (HTML/JS) to React.
This is going pretty well except that I have a problem with the initialization of a carousel (jQuery library) ...
To be clear, I have several components (Children structure below):
-- Home
---- TopProducts
-------- ProductsSlider
--------------- Product
So in the Home component, I integrate the TopProducts component which makes an API call via Axios to get a list of products and passes the result to the ProductsSlider component.
This work well.
Once the API call is finished and the component generated, I need to initialize a carousel by a jquery function.
And this only works if I place the call to this function in the axios ".then" function below the addition to a state variable of the result of the call.
Like that :
useEffect(() => {
axios.get('products/bestsellers')
.then(response => {
setTopProducts(response.data.response);
window.carousel_slider();
});
}, []);
But it is very not clear to have it here( if i have another carousel in the page ... ), so I would like to have the call to this function in my Home component, but it does not work because the useEffect of Home is always called before the rendering of the TopProducts component ...
So i don't know how to call it when everything is rendered, i see that with Class component, the ComponentWillUnmount should work but i would like to use Hooks ...
I know that it is preferable not to use jQuery with React but it would be much too long to convert everything and to look for jquery libraries which does not exist maybe on react ...
I don't know if I have the right way, someone have an idea?
Thank you in advance
if you wrap your axios call in a return, it will behave like componentWillUnmount.
useEffect(() => {
return () => {
axios.get('products/bestsellers')
.then(response => {
setTopProducts(response.data.response);
window.carousel_slider();
});
}
}, [yourDependency]);
I found the problem.
It is because topProducts state is init with empty array and React don't wait the end of useEffect before rendering it, so the carousel_slider() is executed with the empty component.
Just need to check the topProducts state length before rendering :
{topProducts.length > 0 ? (
<ProductsSlider products={topProducts}/>
) : <Spinner />}

Should we change class component to functional component when we put state into Redux?

I was learning React and created two class components having respective states. Then, I learned about Redux and decided to transfer states into redux store. The question is "Is it best practice to change class componenents into functional components since we get state via props from redux store?"
Functional components with react hooks is the new standard of coding on React. For store management(f.e. redux) you may use as classes as functional components, but most of the libs moved to functional components and you may not use all benefits of last versions of them.
Why I prefer functional components and hooks over classes:
Cleaner render tree. No wrapper components
More flexible code. You
can use useEffect on different state changes, in classes you have
only componentDidUpdate for ANY state/props change
You can define your custom hooks to keep your code clean and shiny
IMHO, yes, I suggest that you should switch from class-based component to functional component as soon as possible.You might not want to know how the class-based components have bugged me so hurt before I decided to go with Hooks. The number of components in my large project is now over 400 (including both smart and dumb components) and keep increasing. Hooks keep my life easier to continue developing and maintaining.
Have a look at this useful article: https://blog.bitsrc.io/why-we-switched-to-react-hooks-48798c42c7f
Basically, this is how we manage state with class-based:
It can be simplified to half the lines of code, achieving the same results with functional component and useState, useEffect:
Please also take a look at this super useful site: https://usehooks.com/
There are many useful custom hooks from the community that you can utilize. Below are the ones that I have been using all the time:
useRouter: Make your life easier with react-router. For example:
import { useRouter } from "./myCustomHooks";
const ShowMeTheLocation = () => {
const router = useRouter();
return <div>Show me my param: {router.match.params.myDesiredParam}</div>;
}
useEventListener: simplify your event handler without using componentDidMount and componentWillUnmount to subscribe/unsubscribe. For example, I have a button that needs to bind a keypress event:
import { useEventListener } from "./myCustomHooks";
const FunctionButton = () => {
const keydownHandler = event => { // handle some keydown actions };
const keyupHandler = event => { // handle some keyup actions };
// just simple like this
useEventListener("keydown", keydownHandler);
useEventListener("keyup", keyupHandler);
}
useAuth: authenticate your user.
import { useAuth } from "./use-auth.js";
const Navbar = (props) => {
// Get auth state and re-render anytime it changes
const auth = useAuth();
// if user is authenticated, then show user email, else show Login
return <div>{auth.user? auth.user.email: "Login"}</div>;
}
useRequireAuth: handle redirect your user if they are signed out and trying to view a page that should require them to be authenticated. This is composed by useRouter and useAuth above.
import { useRequireAuth } from "./myCustomHooks";
// Dashboard is a page that need authentication to view
const Dashboard = () => {
const isAuth = useRequireAuth();
// If isAuth is null (still fetching data)
// or false (logged out, above hook will redirect)
// then show loading indicator.
if (isAuth) {
return <div>Fetching data, please wait!</div>
}
// {...{ isAuth }} is similar to:
// isAuth={isAuth}
return <Dashboard {...{ isAuth }} />
}
Hope this helps!
First of All, States can be used only in Class Component. In React's latest version there's a huge update that allows functional components to declare and use state using React-Hooks. So, the best practice I would personally suggest you is to use Class Component when you use the Redux Store. As you're a beginner, Please use a functional component where you don't use any state or props and just render DOM elements (Note: Functional components can accept props). Once you learn the differences properly, go with React-Hooks.
I hope it helps!! Happy Coding!!

Re-render component when navigating the stack with React Navigation

I am currently using react-navigation to do stack- and tab- navigation.
Is it possible to re-render a component every time the user navigates to specific screens? I want to make sure to rerun the componentDidMount() every time a specific screen is reached, so I get the latest data from the server by calling the appropriate action creator.
What strategies should I be looking at? I am pretty sure this is a common design pattern but I failed to see documented examples.
If you are using React Navigation 5.X, just do the following:
import { useIsFocused } from '#react-navigation/native'
export default function App(){
const isFocused = useIsFocused()
useEffect(() => {
if(isFocused){
//Update the state you want to be updated
}
}, [isFocused])
}
The useIsFocused hook checks whether a screen is currently focused or not. It returns a boolean value that is true when the screen is focused and false when it is not.
React Navigation lifecycle events quoted from react-navigation
React Navigation emits events to screen components that subscribe to them. There are four different events that you can subscribe to: willFocus, willBlur, didFocus and didBlur. Read more about them in the API reference.
Let's check this out,
With navigation listeners you can add an eventlistener to you page and call a function each time your page will be focused.
const didBlurSubscription = this.props.navigation.addListener(
'willBlur',
payload => {
console.debug('didBlur', payload);
}
);
// Remove the listener when you are done
didBlurSubscription.remove();
Replace the payload function and change it with your "refresh" function.
Hope this will help.
You can also use also useFocusEffect hook, then it will re render every time you navigate to the screen where you use that hook.
useFocusEffect(()=> {
your code
})
At the request of Dimitri in his comment, I will show you how you can force a re-rendering of the component, because the post leaves us with this ambiguity.
If you are looking for how to force a re-rendering on your component, just update some state (any of them), this will force a re-rendering on the component. I advise you to create a controller state, that is, when you want to force the rendering, just update that state with a random value different from the previous one.
Add a useEffect hook with the match params that you want to react to. Make sure to use the parameters that control your component so it rerenders. Example:
export default function Project(props) {
const [id, setId] = useState(props?.match?.params?.id);
const [project, setProject] = useState(props?.match?.params?.project);
useEffect(() => {
if (props.match) {
setId(props.match?.params.id);
setProject(props.match?.params.project);
}
}, [props.match?.params]);
......
To trigger a render when navigating to a screen.
import { useCallback } from "react";
import { useFocusEffect } from "#react-navigation/native";
// Quick little re-render hook
function useForceRender() {
const [value, setValue] = useState(0);
return [() => setValue(value + 1)];
}
export default function Screen3({ navigation }) {
const [forceRender] = useForceRender();
// Trigger re-render hook when screen is focused
// ref: https://reactnavigation.org/docs/use-focus-effect
useFocusEffect(useCallback(() => {
console.log("NAVIGATED TO SCREEN3")
forceRender();
}, []));
}
Note:
"#react-navigation/native": "6.0.13",
"#react-navigation/native-stack": "6.9.0",

Resources