Add AOS library to react - javascript

I'm trying to add AOS library to react. My code is like this now which is giving me an error that init is undefined:
import './App.css';
import 'bootstrap/dist/css/bootstrap.min.css';
import Menubar from './Components/Menubar/Menubar';
import Products from './Components/Products/Products';
import { useEffect, useState } from 'react';
import 'aos/dist/aos.css'
import { AOS } from 'aos';
function App() {
const [product, setProduct]= useState([]);
useEffect(()=>{
fetch('https://fakestoreapi.com/products')
.then(Response=>Response.json())
.then(data=>setProduct(data))
},[]);
AOS.init();
const [count, setCount]= useState(0);
return (
<div>
<Menubar count={count}></Menubar>
<Products count={count} setCount={setCount} product={product}></Products>
</div>
);
}
export default App;
And when i Try to use the AOS.init() with hook i get 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.
import './App.css';
import 'bootstrap/dist/css/bootstrap.min.css';
import Menubar from './Components/Menubar/Menubar';
import Products from './Components/Products/Products';
import { useEffect, useState } from 'react';
import 'aos/dist/aos.css'
import { AOS } from 'aos';
function App() {
const [product, setProduct]= useState([]);
useEffect(()=>{
fetch('https://fakestoreapi.com/products')
.then(Response=>Response.json())
.then(data=>setProduct(data))
},[]);
useEffect(()=>{
AOS.init();
},[])
const [count, setCount]= useState(0);
return (
<div>
<Menubar count={count}></Menubar>
<Products count={count} setCount={setCount} product={product}></Products>
</div>
);
}
export default App;

Instead of :
import { AOS } from "aos";
Try this :
import AOS from "aos";

Related

react global context is not updating

I am relatively new to react and cant seem to get my global context to update.I have wrapped all my child components with the provider but it seems like my update methods in my useState() variables are not working as expected. In my index.js file, I wrap my App component in the provider first:
import App from './App';
import reportWebVitals from './reportWebVitals';
import {
BrowserRouter,
Route,
Routes
} from "react-router-dom";
import {UserContextProvider} from './components/UserContext';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<UserContextProvider>
<App/>
</UserContextProvider>
);
Here is my UserContext.js file:
import React from "react";
import { useState, createContext } from "react";
export const UserContext = createContext({})
export const UserContextProvider = ({children}) =>{
const [contextUsername, setUserName] = useState(null)
const [contextFirstname, setFirstName] = useState(null)
const [contextLastname, setLastName] = useState(null)
const [contextLoggedin, setLoggedIn] = useState(false)
const value={contextUsername, setUserName, contextFirstname, setFirstName,
contextLastname,setLastName,contextLoggedin,setLoggedIn}
return(
<UserContext.Provider value={value}>
{children}
</UserContext.Provider>
)
}
I am trying to access my context in my Landing component:
import React, { useContext } from 'react';
import { useState } from 'react';
import {Link, useNavigate} from "react-router-dom"
import { UserContext } from './UserContext';
const Landing = () =>{
const {contextUsername,setUserName} = useContext(UserContext)
const onExit = (convertedData) =>{
setUserName("test")
console.log(contextUsername)
navigate('/');
}
return(
<div>
<button onLick={onExit}></button>
</div>
)
}
export default Landing
However, in my console.log statement my contextUsername is 'undefined'.
The update state doesn't work like that. react create a queue for state update so we can not get the latest value right after the update call. since you are console.log(contextUsername) right after setUserName it console's undefined.
and don't pass updateState-method(ex. setUserName) directly in context create method to change state value from there call updateState-method(ex. setUserName) like
const UpdateUserName = (value) =>{
setUserName(value)
}
if you want to check the updated value of contextUsername use useEffect
useEffect(() => {
console.log(contextUsername);
},[contextUsername])

Need to change a state variable within another component in React

I need to change the value mainPageView inside the UserProfile and ChangePassword Components how to achieve that? In further I want to change mainPageView value to false when clicking a button inside the UserProfile and change it to true when clicking a button inside the ChangePassword. Here is my code
import * as React from "react";
import List from "#mui/material/List";
import ListItem from "#mui/material/ListItem";
import ListItemText from "#mui/material/ListItemText";
import ListItemAvatar from "#mui/material/ListItemAvatar";
import Avatar from "#mui/material/Avatar";
import Box from "#mui/material/Box";
import AccountCircleIcon from "#mui/icons-material/AccountCircle";
import Typography from "#mui/material/Typography";
import HomeIcon from "#mui/icons-material/Home";
import CakeIcon from "#mui/icons-material/Cake";
import Axios from "axios";
import { useState, useEffect, useContext } from "react";
import { LoginContext, UserContext } from "../../../Helper/UserContext";
import { Button } from "#mui/material";
import UserProfile from "./Profile";
import ChangePassword from "./Profile";
export default function MainProfile() {
const { cookies } = useContext(LoginContext);
const employee_id = cookies.emp_id;
const [mainPageView, setMainPageView] = useState(true);
return (
<div>
{mainPageView && <UserProfile />}
{!mainPageView && <ChangePassword />}
</div>
);
}
A solution (code snippet) which describes the USerProfile and ChangePassword Component
Pass parent method as a props
e.g.
{mainPageView && <UserProfile updatevalue ={setMainPageView}/>}
{!mainPageView && <ChangePassword updatevalue ={setMainPageView} />}
const ChangePassword = (props) => {
return (
<div>
<h1 onClick= { () =>
props.updatevalue(false>)
}
> Something</h1>
</div>
)
}
export default ChangePassword;

data is null after fetching it from API

I'm trying to make movies app for portfolio, I got an api with some data and I'm trying to fetch it with useEffect and then setting the state, I also use useContext hook for passing data to children props but the data is empty.
This is App.js
import "./App.css";
import { useEffect, useState, createContext } from "react";
import Axios from "axios";
import { Main } from "./components/Main/Main";
export const AppContext = createContext();
function App() {
const [data, setData] = useState([]);
useEffect(() => {
Axios.get("http://www.omdbapi.com/?s=star wars&apikey=459f1ce1").then((res) => {
setData(res.data.Search);
})
}, []);
return (
<div className="App">
<AppContext.Provider value={data}>
<Main />
</AppContext.Provider>
</div>
);
}
export default App;
This is Main.js
import React from "react";
import { useContext } from "react";
import { AppContext } from "../../App";
import "./Main.css";
export const Main = () => {
const { data } = useContext(AppContext);
console.log(data)
return <div>
</div>;
};
export default Main;
Currently the value of the context is just the value of the data state. To be able to destructure the context change your value to an object containing the data.
<AppContext.Provider value={{ data }}>

useReducer with useContext hook behaves weirdly, and runs and infinite loop

I am trying to make a React project which fetches data from an API, and I'm trying to use useReducer hook with useContext from an external file.
Folder Structure:
public
src (and in src folder, I have context.js and reducer.js along with rest of the components and and other files)
package.json
reducer.js:
const reducer = (currentState, action)=>{
switch(action.type){
case 'setBreedList':
// console.log('setBreedList ran')
return {...currentState, breedList: [...currentState.breedList, action.payload]}
// return currentState
// return {...currentState.breedList, action.payload}
default:
return currentState
}
}
export default reducer
context.js
import React, {useContext, useReducer} from 'react';
import reducer from './reducer';
const AppContext = React.createContext();
const initalState = {
breedList: [],
imageList: []
}
const AppProvider = ({children})=>{
const [state, dispatch] = useReducer(reducer, initalState);
const fetchAllBreeds = ()=>{
fetch('https://dog.ceo/api/breeds/list/all')
.then(res=>res.json())
.then(data=>dispatch({type: 'setBreedList', payload: data}))
}
return (
<AppContext.Provider value={{...state, fetchAllBreeds}}>
{children}
</AppContext.Provider>
)
}
export const useGlobalContext = ()=>{
return useContext(AppContext)
}
export {AppContext, AppProvider}
and this is index.js:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import {AppProvider} from './utils/context';
ReactDOM.render(
<React.StrictMode>
<AppProvider>
<App />
</AppProvider>
</React.StrictMode>,
document.getElementById('root')
);
and finally, this is Input.jsx, where I call the fetchAllBreeds function:
import React from 'react'
import {useGlobalContext} from '../utils/context'
const Input = () => {
const {state, fetchAllBreeds} = useGlobalContext();
fetchAllBreeds();
console.log('hello')
return (
<div>
<p>hello</p>
</div>
)
}
export default Input
Now, when I try to call the fetchAllBreeds function in the Input.jsx file above, it prints on the console, 'hello', endlessly. I can't figure out why this is happening and I have tried some different things, but the result is the same. Will be grateful to your help.
Input component is calling fetchAllBreeds function, that will update the context value which in turn will re-render Input component, hence fetchAllBreeds will re-run. Don't call any method inside the component body which will cause re-renders.
Use useEffect hook inside Input component. which will execute only once.
import React, {useEffect} from 'react'
import {useGlobalContext} from '../utils/context'
const Input = () => {
const {state, fetchAllBreeds} = useGlobalContext();
useEffect(()=>{
fetchAllBreeds();
}, [])
return (
<div>
<p>hello</p>
</div>
)
}
export default Input

Uncaught TypeError: Object is not iterable when using useReducer with useContext for global store React js

I am trying to use hooks to replace the redux store with action and reducers
I have created a global store using createContext and a global reducer using useReducer and trying to use the global state object with useContext in the below file which is throwing error. Also, I have tried console logging the return value of useContext(Store) which is giving undefined.
import React, {useContext, useEffect} from 'react'
import {newAction} from './actions'
import Store from '../../utils/store'
const Home = ()=>{
console.log(Store)
const [appStore, dispatch] = useContext(Store)
useEffect(()=>{
dispatch(newAction())
console.log(appStore)
},[])
return(<div>Hello there</div>)
}
export default Home
Getting error index.jsx:7 Uncaught TypeError: Object is not iterable (cannot read property Symbol(Symbol.iterator)) at Home (index.jsx:7) at renderWithHooks (react-dom.development.js:14803) at line const [appStore, dispatch] = useContext(Store)
My App.js
import React from 'react';
import logo from './logo.svg';
import './App.css';
import Home from './pages/home';
import './styles/index.scss'
import {StoreProvider} from './utils/store'
function App() {
return (
<div className="App">
<StoreProvider>
<Home/>
</StoreProvider>
</div>
);
}
export default App;
My Store/index.js
import {createContext} from 'react'
const Store = createContext({});
export const StoreProvider = Store.Provider;
export default Store;
contextProvider.js
import React,{useReducer} from 'react';
import {ContextProvider} from './index'
import reducer from './combineReducer'
const initialState = { home:{} }
const StoreProvider = (props) =>{
return <ContextProvider value={useReducer(reducer, initialState)}>
{props.children}
</ContextProvider>
}
export default StoreProvider
combineReducer.js
import homeReducer from '../../pages/home/reducer'
export default mainReducer = (initialState, action)=>{
return({
home: homeReducer(initialState.home, action)
})
}
home/reducer.js
import {NEW_ACTION} from './actions'
export default reducer = (state,action) =>{
switch(action.type){
case NEW_ACTION: return {...state, val:true}
default: return state
}
}
There were few mistakes in the code in the following files:
in file Store/index.js rename variable StoreProvider to
ContextProvider as i am using ContextProvider which is not defined there.
in file App.js change the import line import {StoreProvider} from './utils/store' to import StoreProvider from './utils/store/contextProvider' as provider is written in contextProvider file.
Files after fixes:
Store/index.js
import {createContext} from 'react'
const Store = createContext({});
export const ContextProvider = Store.Provider;
export default Store;
App.js
import React from 'react';
import logo from './logo.svg';
import './App.css';
import Home from './pages/home';
import './styles/index.scss'
import StoreProvider from './utils/store/contextProvider'
function App() {
return (
<div className="App">
<StoreProvider>
<Home/>
</StoreProvider>
</div>
);
}
export default App;

Categories

Resources