I created a custom hook, Custom.js:
import React, {useState, useEffect} from 'react';
import Clarifai from 'clarifai';
const app = new Clarifai.App({
apiKey: 'XXXXXXXXXXXXXX'
})
const Custom = () => {
const [input, setInput] = useState('');
const [imgUrl, setImgUrl] = useState('');
function onInputChange (text) {
setInput(text);
}
useEffect(()=>{
setImgUrl(input)
}, [input])
function onSubmit () {
console.log('submitted');
console.log(imgUrl)
app.models.predict(Clarifai.COLOR_MODEL, "https://www.takemefishing.org/getmedia/bde1c54e-3a5f-4aa3-af1f-f2b99cd6f38d/best-fishing-times-facebook.jpg?width=1200&height=630&ext=.jpg").then(
function(response) {
console.log(response);
},
function(err) {
// there was an error
}
);
}
return {input, imgUrl, onInputChange, onSubmit}
}
export default Custom;
I imported this custom hook into 2 of my other components, FaceRecognition.js and InputForm.js.
FaceRecognition.js:
import React from 'react';
import Custom from '../Custom';
const FaceRecognition = () => {
const { imgUrl } = Custom();
function yes (){
return console.log(imgUrl)
}
yes()
return (
<div>
<h1 className='white'>The url is {ImgUrl} </h1>
<img width={'50%'} alt=''src={imgUrl}/>
</div>
);
}
export default FaceRecognition;
ImportForm.js:
import React, {useState} from 'react';
import './InputForm.css'
import Custom from '../Custom';
const InputForm = () => {
const { onInputChange, onSubmit } = Custom();
return (
<>
<p className='txt f3'>Enter image link address</p>
<div className='center flex w-70'>
<input type='text' className='w-80 pa1' onChange={(e)=>onInputChange(e.target.value)}/>
<button className='w-20 pa1 pointer' onClick={onSubmit}>Detect</button>
</div>
</>
);
}
export default InputForm;
The functions onSubmit and onImputChange work as expected for InputForm.js and the value of imgUrl logs on the console when function onSubmit runs, as expected. But the imgUrl state which is a string fails to show up between the h1 tags <h1 className='white'>The url is {imgUrl} boy</h1> from my FaceRecognition.js snippet above, and it also doesn't work as the src of the image <img width={'50%'} alt=''src={imgUrl}/> below the h1 tag. This is my problem.
Issue
React hooks don't magically share state. You've two separate instances of this Custom function, each with their own useState hook. I say "function" because you've also mis-named your hook. All React hooks should be named with a "use-" prefix so React can identify it and apply the Rules of Hooks against it.
Solution
If you want separate instances of your useCustom hook to share state then the state needs to be lifted to a common component to be shared. For this you should use a React Context.
Example:
import React, { createContext, useContext, useState, useEffect } from 'react';
import Clarifai from 'clarifai';
const app = new Clarifai.App({
apiKey: 'XXXXXXXXX'
});
const CustomContext = createContext({
input: '',
imgUrl: '',
onInputChange: () => {},
onSubmit: () => {}
});
const useCustom = () => useContext(CustomContext);
const CustomProvider = ({ children }) => {
const [input, setInput] = useState('');
const [imgUrl, setImgUrl] = useState('');
function onInputChange (text) {
setInput(text);
}
useEffect(()=>{
setImgUrl(input);
}, [input]);
function onSubmit () {
console.log('submitted');
console.log(imgUrl);
app.models.predict(
Clarifai.COLOR_MODEL,
"https://www.takemefishing.org/getmedia/bde1c54e-3a5f-4aa3-af1f-f2b99cd6f38d/best-fishing-times-facebook.jpg?width=1200&height=630&ext=.jpg"
).then(
function(response) {
console.log(response);
},
function(err) {
// there was an error
}
);
}
return (
<CustomContext.Provider value={{ input, imgUrl, onInputChange, onSubmit }}>
{children}
</CustomContext.Provider>
);
}
export {
CustomContext,
useCustom
};
export default CustomProvider;
Usage:
Wrap your app with your CustomProvider component.
import CustomProvider from '../path/to/CustomProvider';
...
return (
<CustomProvider>
<App />
</CustomProvider>
);
Import and use the useCustom hook in consumers.
import React from 'react';
import { useCustom } from '../path/to/CustomProvider';
const FaceRecognition = () => {
const { imgUrl } = useCustom();
useEffect(() => {
console.log(imgUrl);
});
return (
<div>
<h1 className='white'>The url is {ImgUrl}</h1>
<img width={'50%'} alt='' src={imgUrl}/>
</div>
);
}
export default FaceRecognition;
...
import React, {useState} from 'react';
import './InputForm.css'
import { useCustom } from '../path/to/CustomProvider';
const InputForm = () => {
const { onInputChange, onSubmit } = useCustom();
return (
<>
<p className='txt f3'>Enter image link address</p>
<div className='center flex w-70'>
<input
type='text'
className='w-80 pa1'
onChange={(e) => onInputChange(e.target.value)}
/>
<button
className='w-20 pa1 pointer'
onClick={onSubmit}
>
Detect
</button>
</div>
</>
);
}
export default InputForm;
try to put your return statement inside the .then of the predict
Related
I have react project generated by vite, I get this error when I add eventListener to the DOM. I also use React context API. But I think there might be a problem with the StateProvider.jsx that contains the context API but I'm not sure.
The error says:
Cannot update a component (`StateProvider`) while rendering a different component (`DeltaY`). To locate the bad setState() call inside `DeltaY`, follow the stack trace as described in ...
Here is the snapshot of the error in the console:
Here is the code:
main.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import './index.css';
import { StateProvider } from './StateProvider.jsx';
import reducer, { initialState } from './reducer';
ReactDOM.createRoot(document.getElementById('root')).render(
<StateProvider initialState={initialState} reducer={reducer}>
<App />
</StateProvider>,
);
App.jsx
import './App.css';
import DeltaY from './DeltaY';
import { useStateValue } from './StateProvider';
function App() {
return (
<>
<DeltaY />
<Desc />
</>
);
}
const Desc = () => {
const [{ deltaY, scrollMode }, dispatch] = useStateValue();
return (
<>
<h1> deltaY: {deltaY} </h1>
<h1> scroll: {scrollMode} </h1>
</>
);
};
export default App;
DeltaY.jsx
import { useEffect, useState } from 'react';
import { useStateValue } from './StateProvider';
const DeltaY = () => {
// ------------------------------ context API ------------------------------- //
const [{ state }, dispatch] = useStateValue();
// ------------------------------ context API ------------------------------- //
const [scrollMode, setScrollMode] = useState(false);
const [deltaY, setDeltaY] = useState(0);
useEffect(() => {
function handleWheel(e) {
setDeltaY(e.deltaY);
setScrollMode(true);
}
window.addEventListener('wheel', handleWheel);
return () => window.removeEventListener('wheel', handleWheel);
}, []);
useEffect(() => {
setTimeout(() => {
setScrollMode(true);
}, 1000);
}, []);
// ------------------------------ dispatch ------------------------------- //
dispatch({
type: 'GET_DELTAY',
value: deltaY,
});
dispatch({
type: 'GET_SCROLLMODE',
value: scrollMode,
});
// ------------------------------ dispatch ------------------------------- //
return null;
};
export default DeltaY;
StateProvider.jsx
import React, { createContext, useContext, useReducer } from 'react';
// prepare the daya layer
export const StateContext = createContext();
// Wrap our app and provide the data layer
export const StateProvider = ({ reducer, initialState, children }) => {
return (
<>
<StateContext.Provider value={useReducer(reducer, initialState)}>
{children}
</StateContext.Provider>
</>
);
};
// PUll the information from the data layer
export const useStateValue = () => useContext(StateContext);
Any Idea how to fix it ? thankyou
Here is the solution:
instead of using it as a component, I use it as a custom Hook
Here is the code:
useDeltaY.jsx
import { useEffect, useState } from 'react';
const useDeltaY = () => {
const [scrollMode, setScrollMode] = useState(false);
const [deltaY, setDeltaY] = useState(0);
useEffect(() => {
function handleWheel(e) {
setDeltaY(e.deltaY);
setScrollMode(true);
}
window.addEventListener('wheel', handleWheel);
return () => window.removeEventListener('wheel', handleWheel);
}, []);
useEffect(() => {
setTimeout(() => {
setScrollMode(false);
}, 1000);
}, [scrollMode]);
return [deltaY, scrollMode];
};
export default useDeltaY;
App.jsx
import './App.css';
import useDeltaY from './useDeltaY';
function App() {
return (
<>
<Desc />
</>
);
}
const Desc = () => {
const [deltaY, scrollMode] = useDeltaY();
return (
<>
<h1> deltaY: {deltaY} </h1>
{scrollMode ? (
<h1> scrollMode: active </h1>
) : (
<h1> scrollMode: inActive </h1>
)}
</>
);
};
export default App;
Having this React function, tried to run a test but it doesn't pass it:
import React, { useEffect } from 'react';
import { useDispatch, useSelector, shallowEqual } from 'react-redux';
import { useIntl } from 'react-intl';
import {
PrimaryButton,
OutlineButton
} from 'react-komodo-design';
const Buttons = () => {
const dispatch = useDispatch();
const intl = useIntl();
const orderType = useSelector(
(state) => state.orderDetails.orderDetails.orderType,
shallowEqual
);
...
return (
<div>
<OutlineButton>
{intl.formatMessage({ id: 'buttons' })}
</OutlineButton>
{orderType.toLowerCase() !== 't9' && (
<PrimaryButton
onClick={clickReorder}
</PrimaryButton>
)}
</div>
);
};
export default Buttons;
The test file is this:
import React from 'react';
import { render } from '#testing-library/react';
import Buttons from './Buttons';
import { WrapIntlProvider, WrapStore } from '../../testsHelper';
describe('<Buttons />', function () {
it('should render <Buttons></Buttons>', () => {
const { container } = render(
<WrapStore>
<WrapIntlProvider>
<Buttons />
</WrapIntlProvider>
</WrapStore>
);
expect(container).toMatchSnapshot();
});
});
Error message: TypeError: Cannot read property 'toLowerCase' of undefined
What can be done to avoid this error?
I've tried to add values inside the test function like this:
<Buttons orderType="test" /> or <Buttons orderType={"test'} /> or send it as a variable:
describe('<Buttons />', function () {
it('should render <Buttons></Buttons>', () => {
const xx = "test"; // <--- added here
const { container } = render(
<WrapStore>
<WrapIntlProvider>
<Buttons orderType={xx} />
</WrapIntlProvider>
</WrapStore>
);
expect(container).toMatchSnapshot();
});
});
import * as redux from 'react-redux'
const spy = jest.spyOn(redux, 'useSelector')
spy.mockReturnValue({ orderType:'test' })
Try to mock useSelector like this.
I am have been working on a little project to better understand react. I recently converted it to use hooks and I am trying to implement redux, with it. However I get the following error now.
TypeError: searchField.toLowerCase is not a function
looking at the docs, I stopped using connect from react-redux and switched to using useDispatch and useSelector. But I believe I have set up everything correctly but not sure as to why this error being raise.
This is my action.js
import { SEARCH_EVENT } from './searchfield_constants';
export const setSearchField = (payload) => ({ type: SEARCH_EVENT, payload });
This is my reducer
import { SEARCH_EVENT } from './searchfield_constants';
const initialState = {
searchField: '',
};
export const searchRobots = (state = initialState, action = {}) => {
switch (action.type) {
case SEARCH_EVENT:
return { ...state, searchField: action.payload };
default:
return state;
}
};
this is my index.js where I am using the Provider from react-redux
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore } from 'redux';
import { searchRobots } from './searchfield/searchfield_reducers';
import './styles/index.css';
import App from './App';
const store = createStore(searchRobots);
ReactDOM.render(
<React.StrictMode>
<Provider store={store}>
<App />
</Provider>
</React.StrictMode>,
document.getElementById('root')
);
finally here is my App.jsx
import { useState, useEffect, useCallback } from 'react';
import { setSearchField } from './searchfield/searchfield_actions';
import { useDispatch, useSelector } from 'react-redux';
import axios from 'axios';
import React from 'react';
import CardList from './components/CardList';
import SearchBox from './components/SearchBox';
import Scroll from './components/Scroll';
import Error from './components/Error';
import 'tachyons';
import './styles/App.css';
// const mapStateToProps = (state) => ({
// searchField: state.searchField,
// });
// const mapDispatchToProps = (dispatch) => ({
// onSearchChange: (e) => dispatch(setSearchField(e.target.value)),
// });
const App = () => {
const searchField = useSelector(state => state.searchField)
const dispatch = useDispatch();
const [robots, setRobots] = useState([]);
// const [searchField, setSearchField] = useState('');
const fetchUsers = useCallback(async () => {
try {
const result = await axios('//jsonplaceholder.typicode.com/users');
setRobots(result.data);
} catch (error) {
console.log(error);
}
}, []); // eslint-disable-line react-hooks/exhaustive-deps
useEffect(() => {
fetchUsers();
}, []); // eslint-disable-line react-hooks/exhaustive-deps
const filteredRobots = robots.filter((robot) => {
return robot.name.toLowerCase().includes(searchField.toLowerCase());
});
return !robots.length ? (
<h1 className='f1 tc'>Loading...</h1>
) : (
<div className='App tc'>
<h1 className='f1'>RoboFriends</h1>
<SearchBox searchChange={dispatch(setSearchField(e => e.target.value))} />
<Scroll>
<Error>
<CardList robots={filteredRobots} />
</Error>
</Scroll>
</div>
);
};
export default App;
what am I doing wrong?
So the solution was the following,
I created a function called on searchChange, which calls dispatch and then the setSearchField which uses the e.target.value as the payload.
const onSearchChange = (e) => {
dispatch(setSearchField(e.target.value));
};
so the final return looks like the following
return !robots.length ? (
<h1 className='f1 tc'>Loading...</h1>
) : (
<div className='App tc'>
<h1 className='f1'>RoboFriends</h1>
<SearchBox searchChange={onSearchChange} />
<Scroll>
<Error>
<CardList robots={filteredRobots} />
</Error>
</Scroll>
</div>
);
};
In you App.js, convert this line
const searchField = useSelector(state => state.searchField)
to
const { searchField } = useSelector(state => state.searchField)
basically de-structure out searchField from state.searchField
This is attributed to the fact how redux sets state.
In your reducer searchRobots the initial state provided by redux will be
state = {
...state,
searchField
}
and in this line return { ...state, searchField: action.payload };, you're adding
another property searchField to state.searchField object so you'll need to de-structure it out.
It looks like your searchField value is getting set to undefined or some non-string value.
I found this line to be incorrect
<SearchBox searchChange={dispatch(setSearchField(e => e.target.value))} />
It should be changed to
<SearchBox searchChange={() => dispatch(setSearchField(e => e.target.value))} />
So that on search change this function can be called. Currently you are directly calling dispatch and this may be setting your searchField to undefined
Also for safer side before using toLowerCase() convert it to string ie searchField.toString().toLowerCase()
In my Main.js I create a first global state with a username and a list of users I'm following.
Then, both the Wall component and FollowingSidebar render the list of follows and their messages (plus the messages of the main user).
So far so good. But in a nested component inside FollowingSidebar called FollowingUser I have an onClick to remove a user. My understanding is that, because I change the state, useEffect would take care of the Wall component to re-render it, but nothing happens... I've checked several examples online but nothing has helped my use case so far.
Needless to say I'm not overly experienced with React and Hooks are a bit complex.
The code here:
Main.js:
import React, { useEffect, useState } from "react";
import ReactDom from "react-dom";
import db from "./firebase.js";
// Components
import Header from "./components/Header";
import FollowingSidebar from "./components/FollowingSidebar";
import SearchUsers from "./components/SearchUsers";
import NewMessageTextarea from "./components/NewMessageTextarea";
import Wall from "./components/Wall";
// Context
import StateContext from "./StateContext";
function Main() {
const [mainUser] = useState("uid_MainUser");
const [follows, setFollows] = useState([]);
const setInitialFollows = async () => {
let tempFollows = [mainUser];
const user = await db.collection("users").doc(mainUser).get();
user.data().following.forEach(follow => {
tempFollows.push(follow);
});
setFollows(tempFollows);
};
useEffect(() => {
setInitialFollows();
}, []);
const globalValues = {
mainUserId: mainUser,
followingUsers: follows
};
return (
<StateContext.Provider value={globalValues}>
<Header />
<FollowingSidebar />
<SearchUsers />
<NewMessageTextarea />
<Wall />
</StateContext.Provider>
);
}
ReactDom.render(<Main />, document.getElementById("app"));
if (module.hot) {
module.hot.accept();
}
FollowingSidebar component:
import React, { useState, useEffect, useContext } from "react";
import db from "../firebase.js";
import StateContext from "../StateContext";
import FollowingUser from "./FollowingUser";
export default function FollowingSidebar() {
const { followingUsers } = useContext(StateContext);
const [users, setUsers] = useState(followingUsers);
useEffect(() => {
const readyToRender = Object.values(followingUsers).length > 0;
if (readyToRender) {
db.collection("users")
.where("uid", "in", followingUsers)
.get()
.then(users => {
setUsers(users.docs.map(user => user.data()));
});
}
}, [followingUsers]);
return (
<section id="following">
<div className="window">
<h1 className="window__title">People you follow</h1>
<div className="window__content">
{users.map((user, index) => (
<FollowingUser avatar={user.avatar} username={user.username} uid={user.uid} key={index} />
))}
</div>
</div>
</section>
);
}
FollowingUser component:
import React, { useState, useContext } from "react";
import db from "../firebase.js";
import firebase from "firebase";
import StateContext from "../StateContext";
export default function FollowingUser({ avatar, username, uid }) {
const { mainUserId, followingUsers } = useContext(StateContext);
const [follows, setFollows] = useState(followingUsers);
const removeFollow = e => {
const userElement = e.parentElement;
const userToUnfollow = userElement.getAttribute("data-uid");
db.collection("users")
.doc(mainUserId)
.update({
following: firebase.firestore.FieldValue.arrayRemove(userToUnfollow)
})
.then(() => {
const newFollows = follows.filter(follow => follow !== userToUnfollow);
setFollows(newFollows);
});
userElement.remove();
};
return (
<article data-uid={uid} className="following-user">
<figure className="following-user__avatar">
<img src={avatar} alt="Profile picture" />
</figure>
<h2 className="following-user__username">{username}</h2>
<button>View messages</button>
{uid == mainUserId ? "" : <button onClick={e => removeFollow(e.target)}>Unfollow</button>}
</article>
);
}
Wall component:
import React, { useState, useEffect, useContext } from "react";
import db from "../firebase.js";
import Post from "./Post";
import StateContext from "../StateContext";
export default function Wall() {
const { followingUsers } = useContext(StateContext);
const [posts, setPosts] = useState([]);
useEffect(() => {
console.log(followingUsers);
const readyToRender = Object.values(followingUsers).length > 0;
if (readyToRender) {
db.collection("posts")
.where("user_id", "in", followingUsers)
.orderBy("timestamp", "desc")
.get()
.then(posts => setPosts(posts.docs.map(post => post.data())));
}
}, [followingUsers]);
return (
<section id="wall">
<div className="window">
<h1 className="window__title">Latest messages</h1>
<div className="window__content">
{posts.map((post, index) => (
<Post avatar={post.user_avatar} username={post.username} uid={post.user_id} body={post.body} timestamp={post.timestamp.toDate().toDateString()} key={index} />
))}
</div>
</div>
</section>
);
}
StateContext.js:
import { createContext } from "react";
const StateContext = createContext();
export default StateContext;
The main issue is the setting of state variables in the Main.js file (This data should actually be part of the Context to handle state globally).
Below code would not update our state globally.
const globalValues = {
mainUserId: mainUser,
followingUsers: follows
};
We have to write state in a way that it get's modified on the Global Context level.
So within your Main.js set state like below:
const [globalValues, setGlobalValues] = useState({
mainUserId: "uid_MainUser",
followingUsers: []
});
Also add all your event handlers in the Context Level in Main.js only to avoid prop-drilling and for better working.
CODESAND BOX DEMO: https://codesandbox.io/s/context-api-and-rendereing-issue-uducc
Code Snippet Demo:
import React, { useEffect, useState } from "react";
import FollowingSidebar from "./FollowingSidebar";
import StateContext from "./StateContext";
const url = "https://jsonplaceholder.typicode.com/users";
function App() {
const [globalValues, setGlobalValues] = useState({
mainUserId: "uid_MainUser",
followingUsers: []
});
const getUsers = async (url) => {
const response = await fetch(url);
const data = await response.json();
setGlobalValues({
...globalValues,
followingUsers: data
});
};
// Acts similar to componentDidMount now :) Called only initially
useEffect(() => {
getUsers();
}, []);
const handleClick = (id) => {
console.log(id);
const updatedFollowingUsers = globalValues.followingUsers.filter(
(user) => user.id !== id
);
setGlobalValues({
...globalValues,
followingUsers: updatedFollowingUsers
});
};
return (
<StateContext.Provider value={{ globalValues, handleClick }}>
<FollowingSidebar />
</StateContext.Provider>
);
}
export default App;
I built a simple react app that fetch the users from database like mysql
After fetching data I want to pass data to child component and it works sometimes but when refresh page it throw error like data.map is not function
here error message image
my code of parent component
import React,{useEffect, useState ,Context, createContext} from 'react'
import Sidenav from '../components/Sidenav'
import {makeStyles} from '#material-ui/core/styles';
import Content from '../components/ContentParent'
import RightSideNav from '../components/RightSideNav'
import Backdrop from '#material-ui/core/Backdrop';
import Async from 'react-async';
import CircularProgress from '#material-ui/core/CircularProgress';
import { get } from 'js-cookie';
const bodyData = createContext()
const useStyles = makeStyles((theme) => ({
HomeDataContainer_parent:{
backgroundColor:'#F2F2F2',
display:'flex',
},
backdrop: {
zIndex: theme.zIndex.drawer + 1,
color: '#fff',
},
}))
function HomeDataContainer() {
const [data,setData] = useState('')
const [isload,setload] = useState(true)
useEffect(() =>{
async function get(){
fetch('/postsDrawer').then(async data => await data.json()).then(result =>{ setData(result)
setload(false)
})
}
get()
},[data])
const classes = useStyles()
return (
<div className = {classes.HomeDataContainer_parent}>
<Backdrop className={classes.backdrop} open={isload} >
<CircularProgress color="inherit" />
</Backdrop>
{/* sidenav */}
<Sidenav/>
{/* content */}
if(data){
<Content value = {data} />
}
{/* Right side updates */}
<RightSideNav />
</div>
)
}
export default HomeDataContainer
export { bodyData }
child component
import React from 'react'
import {makeStyles} from '#material-ui/core/styles'
import Avatar from '#material-ui/core/Avatar';
import ArrowDropDownTwoToneIcon from '#material-ui/icons/ArrowDropDownTwoTone';
import ArrowDropUpTwoToneIcon from '#material-ui/icons/ArrowDropUpTwoTone';
import LocalOfferTwoToneIcon from '#material-ui/icons/LocalOfferTwoTone';
import Chip from '#material-ui/core/Chip';
import QuestionAnswerIcon from '#material-ui/icons/QuestionAnswer';
import VisibilityIcon from '#material-ui/icons/Visibility';
import Logo from '../images/action.png'
import { BodyData } from '../components/HomeDataContainer'
export default function HomeRecentQuestion(props) {
const classes = useStyles()
const data = props.value
let count = 0
return (
data.map(content => {
let count = content.tags.split(',')
return (
<h1>{content.id}</h1>
)
})
)
}
how to resolve this
1:
Change your data state to this:
const [data,setData] = useState([])
Change useEffect to this:
useEffect(() =>{
if(!data.length)
fetch('/postsDrawer').then(res=> res.json())
.then(result => {
setData(result)
setload(false)
})
},[data])
Change your component to this:
<HomeRecentQuestion value={data} />
You can try using below on the child component.
data && data.map(content => {
let count = content.tags.split(',')
return (
<h1>{content.id}</h1>
)
})
you will change it state of types when you created
like these: const [data, setData] = useState([]);
just you can it than problem will close it.