I have this component in which I want to update a state and make an array with al the users connected in a room from an incoming msg from socket.on:
export default function ChatRoom() {
const [users, setUsers] = useState([]);
const { state } = useLocation(); //to get data from <Home/> component
socket.on("message", (msg) => console.log(msg));
useEffect(() => {
if (state.connected) {
socket.on("userconnected", (msg) => {
setUsers((old) => [...old, msg]);
console.log(state.username);
});
}
}, [state.connected, users]);
The username is coming from another component state in which I send a msg to the server:
export default function Home() {
const [username, setUsername] = useState("");
const [room, setRoom] = useState("");
const [connected, setConnected] = useState(false);
useEffect(() => {
if (connected && room && username) {
navigate("/chatroom", {
state: { username, room, connected },
});
}
}, [connected, room, username]);
const navigate = useNavigate();
const handleClick = (e) => {
e.preventDefault();
socket.emit("connected", username);
setConnected(true);
};
The problem is that I cant update the state with setUsers. I think it has to do with an async problem but I can´t figure it out. Basically I need an array with all the users that are connected.
Related
When I load my Nextjs page, I get this error message: "Error: Rendered more hooks than during the previous render."
If I add that if (!router.isReady) return null after the useEffect code, the page does not have access to the solutionId on the initial load, causing an error for the useDocument hook, which requires the solutionId to fetch the document from the database.
Therefore, this thread does not address my issue.
Anyone, please help me with this issue!
My code:
const SolutionEditForm = () => {
const [formData, setFormData] = useState(INITIAL_STATE)
const router = useRouter()
const { solutionId } = router.query
if (!router.isReady) return null
const { document } = useDocument("solutions", solutionId)
const { updateDocument, response } = useFirestore("solutions")
useEffect(() => {
if (document) {
setFormData(document)
}
}, [document])
return (
<div>
// JSX code
</div>
)
}
useDocument hook:
export const useDocument = (c, id) => {
const [document, setDocument] = useState(null)
const [isLoading, setIsLoading] = useState(true)
const [error, setError] = useState(null)
useEffect(() => {
const ref = doc(db, c, id)
const unsubscribe = onSnapshot(
ref,
(snapshot) => {
setIsLoading(false)
if (snapshot.data()) {
setDocument({ ...snapshot.data(), id: snapshot.id })
setError(null)
} else {
setError("No such document exists")
}
},
(err) => {
console.log(err.message)
setIsLoading(false)
setError("failed to get document")
}
)
return () => unsubscribe()
}, [c, id])
return { document, isLoading, error }
}
You cannot call a hook, useEffect, your custom useDocument, or any other after a condition. The condition in your case is this early return if (!router.isReady) returns null. As you can read on Rules of Hooks:
Don’t call Hooks inside loops, conditions, or nested functions. Instead, always use Hooks at the top level of your React function, before any early returns...
Just remove that if (!router.isReady) returns null from SolutionEditForm and change useDocument as below.
export const useDocument = (c, id) => {
const [document, setDocument] = useState(null);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
if (!id) return; // if there is no id, do nothing 👈🏽
const ref = doc(db, c, id);
const unsubscribe = onSnapshot(
ref,
(snapshot) => {
setIsLoading(false);
if (snapshot.data()) {
setDocument({ ...snapshot.data(), id: snapshot.id });
setError(null);
} else {
setError("No such document exists");
}
},
(err) => {
console.log(err.message);
setIsLoading(false);
setError("failed to get document");
}
);
return () => unsubscribe();
}, [c, id]);
return { document, isLoading, error };
};
The if (!router.isReady) return null statement caused the function to end early, and subsequent hooks are not executed.
You need to restructure your hooks such that none of them are conditional:
const [formData, setFormData] = useState(INITIAL_STATE)
const router = useRouter()
const { solutionId } = router.query
const { document } = useDocument("solutions", solutionId, router.isReady) // pass a flag to disable until ready
const { updateDocument, response } = useFirestore("solutions")
useEffect(() => {
if (document) {
setFormData(document)
}
}, [document])
// Move this to after the hooks.
if (!router.isReady) return null
and then to make useDocument avoid sending extra calls:
export const useDocument = (c, id, enabled) => {
and updated the effect with a check:
useEffect(() => {
if (!enabled) return;
const ref = doc(db, c, id)
const unsubscribe = onSnapshot(
ref,
(snapshot) => {
setIsLoading(false)
if (snapshot.data()) {
setDocument({ ...snapshot.data(), id: snapshot.id })
setError(null)
} else {
setError("No such document exists")
}
},
(err) => {
console.log(err.message)
setIsLoading(false)
setError("failed to get document")
}
)
return () => unsubscribe()
}, [c, id, enabled])
UseEffect cannot be called conditionally
UseEffect is called only on the client side.
If you make minimal representation, possible to try fix this error
I have created an input field with a search term which creates a request to a backend API. To summarise, two issues:
It fetches data from my API, but it fetches ALL roles, not just ones filtered by the term.
It does not commit to the redux store.
Please see my app, it contains simply:
This is my frontend component, which is making an action dispatch based on a search term.
export function SearchBarTrialRedux(props) {
const [isExpanded, setExpanded] = useState(false);
const [parentRef, isClickedOutside ] = useClickOutside();
const inputRef = useRef();
const [searchQuery, setSearchQuery] = useState("");
const [isLoading, setLoading] = useState(false);
const [jobPostings, setjobPostings] = useState([]);
const [noRoles, setNoRoles] = useState(false)
const isEmpty = !jobPostings || jobPostings.length === 0;
const expandedContainer = () => {
setExpanded(true);
}
const collapseContainer = () => {
setExpanded(false);
setSearchQuery("");
setLoading(false);
setNoRoles(false);
if (inputRef.current) inputRef.current.value = "";
};
useEffect(()=> {
if(isClickedOutside)
collapseContainer();
}, [isClickedOutside])
const [term, setTerm] = useState("")
const dispatch = useDispatch();
const changeHandler = (e) => {
e.preventDefault();
fetchAsyncRoles(dispatch, {term});
}
return (
<SearchBarContainer animate = {isExpanded ? "expanded" : "collapsed"}
variants={containerVariants} transition={containerTransition} ref={parentRef}>
<SearchInputContainer>
<SearchIconSpan>
<SearchIcon/>
</SearchIconSpan>
<form onSubmit={changeHandler}>
<SearchInput placeholder = "Search for Roles"
onFocus={expandedContainer}
ref={inputRef}
value={term}
onChange={(e)=> setTerm(e.target.value)}
/>
</form>
</SearchBarContainer>
And my jobsearchSlice
import { createSlice, createAsyncThunk } from "#reduxjs/toolkit";
import { publicRequest } from "../requestMethods";
export const fetchAsyncRoles = async (dispatch, term) => {
dispatch(searchStart());
try {
const res = await publicRequest.get(`http://localhost:5000/api/role/titlerole?title=${term}`);
dispatch(searchSuccess(res.data));
console.log(res.data)
} catch (err) {
dispatch(searchFailure());
}
};
const jobsearchSlice = createSlice({
name: "jobsearchSlice",
initialState: {
isFetching: false,
roles: [],
error: false,
},
reducers: {
searchStart: (state) => {
state.isFetching = true;
},
searchSuccess: (state, action) => {
state.isFetching = false;
state.roles = action.payload;
},
searchFailure: (state) => {
state.isFetching = false;
state.error = true;
},
},
});
export const { searchStart, searchSuccess, searchFailure } = jobsearchSlice.actions;
export default jobsearchSlice.reducer;
As stated, it does create and fetch this data. This does commit it to the store under the roles key, which is great! That's what I want, however it is not filtering. E.g If we look at a role specifically like Data Scientist:
https://gyazo.com/ca4c2b142771edd060a7563b4200adf8
I should be getting just 1 key, Data Scientist.
Looking at the backend of the console.log(res), I can see that it appears my term isn't properly coming through and filtering my roles :
responseURL: "http://localhost:5000/api/role/titlerole?title=[object%20Object]"
But if I log the term, it does come through exactly as input.
What's wrong, what am I doing and how should I solve this term flowing through to filter my req?
I can confirm that if I do this on postman it works...
https://gyazo.com/10f2946c1a3807370b4792c06292b557
Here is the code of the snippet I want to change to a Functional component, I write almost my code here now please check.
import _ from 'lodash';
import { ListItem, SearchBar, Avatar } from 'react-native-elements';
import { getUsers, contains } from './api/index';
function App(props) {
const [loading, setLoading] = useState(false);
const [data, setData] = useState([]);
const [error, setError] = useState(null);
const [fullData, setFullData] = useState([]);
const [query, setQuery] = useState();
useEffect(() => {
makeRemoteRequest();
},[query]);
const makeRemoteRequest = _.debounce(() => {
setLoading(true);
getUsers(20, query)
.then((users) => {
setLoading(false);
setData(users);
setFullData(users);
})
.catch((error) => {
setLoading(false);
});
}, 250);
const handleSearch = (text) => {
const formattedQuery = text.toLowerCase();
const data = _.filter(fullData, (user) => {
return contains(user, formattedQuery);
});
// I want to change the below code to work on Functioanl component
// this.setState({ data, query: text }, () => //this.makeRemoteRequest());
// New code here.....
};
I implemented it in a different way but not work.
You can have something like the following.
const [query, setQuery] = useState();
const [data, setData] = useState();
useEffect(() => {
makeRemoteRequest();
}, [query])
Read more about useEffect here
You're trying to make a set of data and text, then call a callback after the set.
There are several ways to obtain this behaviour.
What I would suggest you is to have a state (useState) which include data and text and then listen for the changes of this stage through a useEffect.
export default function App() {
const [request, setRequest] = useState({data: {}, text: ''});
const makeRemoteRequest = useCallback(() => console.log({request}),[request]);
useEffect(() => {
//on mount
setRequest({data: {obj:'with data'}, text: 'text'})
},[])
useEffect(() => {
makeRemoteRequest()
},[request,makeRemoteRequest])
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
</div>
);
}
What you can see here, it's a functional component which is:
setting a state on mount (read comment)
define a function makeRemoteRequest every time the state request changes through the useCallback hook
call the function makeRemoteRequest every time the state request or the callback makeRemoteRequest changes through the useEffect hook
EDIT:
import _ from 'lodash';
import { ListItem, SearchBar, Avatar } from 'react-native-elements';
import { getUsers, contains } from './api/index';
function App(props) {
const [loading, setLoading] = useState(false);
const [data, setData] = useState([]);
const [error, setError] = useState(null);
const [fullData, setFullData] = useState([]);
const [query, setQuery] = useState();
useEffect(() => {
makeRemoteRequest();
},[query]);
const makeRemoteRequest = _.debounce(() => {
setLoading(true);
getUsers(20, query)
.then((users) => {
setLoading(false);
setData(users);
setFullData(users);
})
.catch((error) => {
setLoading(false);
});
}, 250);
const handleSearch = (text) => {
const formattedQuery = text.toLowerCase();
const data = _.filter(fullData, (user) => {
return contains(user, formattedQuery);
});
setData(data);
setQuery(text);
}
};
Actually what you want is to trigger the function makeRemoteRequest, right now that you have to do in order to get it is to make the proper set (which means setQuery), which is going to trigger the useEffect
I have a component I want to redirect to using react router. How can I set the state of the new component with a string that I chose on the original component? All of my redirects using react router are working and this component that is being redirected to isn't working. It is a html button when clicked should render this new components with initial data.
const Posts = (props) => {
const dispatch = useDispatch();
const getProfile = async (member) => {
console.log(member)
props.history.push('/member', { user: member});
console.log('----------- member------------')
}
const socialNetworkContract = useSelector((state) => state.socialNetworkContract)
return (
<div>
{socialNetworkContract.posts.map((p, index) => {
return <tr key={index}>
<button onClick={() => getProfile(p.publisher)}>Profile</button>
</tr>})}
</div>
)
}
export default Posts;
This is the component I am trying to redirect to on click.
const Member = (props)=> {
const [user, setUser] = useState({});
const { state } = this.props.history.location;
const socialNetworkContract = useSelector((state) => state.socialNetworkContract)
useEffect(async()=>{
try {
await setUser(state.user)
console.log(user)
console.log(user)
const p = await incidentsInstance.usersProfile(state.user, { from: accounts[0] });
const a = await snInstance.getUsersPosts(state.user, { from: accounts[0] });
} catch (e) {
console.error(e)
}
}, [])
I get the following error in the console.
TypeError: Cannot read property 'props' of undefined
Member
src/components/profiles/member.js:16
13 | const [posts, setPosts] = useState([]);
14 | const [snInstance, setsnInstance] = useState({});
15 | const [accounts, setsAccounts] = useState({});
> 16 | const { state } = this.props.history.location;
If you need to send some route state then the push method takes an object.
const getProfile = (member) => {
console.log(member)
props.history.push({
pathname: '/member',
state: {
user: member,
},
});
console.log('----------- member------------')
}
Additionally, Member is a functional component, so there is no this, just use the props object.
The route state is on the location prop, not the history object.
const Member = (props)=> {
const [user, setUser] = useState({});
const { state } = props.location;
// access state.user
Also additionally, useEffect callbacks can't be async as these imperatively return a Promise, interpreted as an effect cleanup function. You should declare an internal async function to invoke. On top of this, the setuser function isn't async so it can't be awaited on.
The following is what I think should be the effects for populating the user state and issuing side-effects:
// update user state when route state updates
useEffect(() => {
if (state && state.user) {
setUser(state.user);
}
}, [state]);
// run effect when user state updates
useEffect(() => {
const doEffects = async () => {
try {
const p = await incidentsInstance.usersProfile(state.user, { from: accounts[0] });
const a = await snInstance.getUsersPosts(state.user, { from: accounts[0] });
} catch (e) {
console.error(e)
}
}
doEffects();
}, [user]);
As the title said, what is the correct way of using custom hook to handle onClick Event?
This codesandbox application will display a new quote on the screen when user clicks the search button.
function App() {
const [{ data, isLoading, isError }, doFetch] = useDataApi(
"https://api.quotable.io/random"
);
return (
<Fragment>
<button disabled={isLoading} onClick={doFetch}>
Search
</button>
{isError && <div>Something went wrong ...</div>}
{isLoading ? <div>Loading ...</div> : <div>{data.content}</div>}
</Fragment>
);
}
I created a custom hook called useDataApi() which would fetch a new quote from an API. In order to update the quote when the user clicks the button, inside the useDataApi(), I created a handleClick() which will change the value of a click value to trigger re-render. And this handleClick() function will be return back to App()
const useDataApi = initialUrl => {
const [data, setData] = useState("");
const [click, setClick] = useState(true);
const [isLoading, setIsLoading] = useState(false);
const [isError, setIsError] = useState(false);
const handleClick = () => {
setClick(!click);
};
useEffect(() => {
const fetchData = async () => {
setIsError(false);
setIsLoading(true);
try {
const result = await axios(initialUrl);
setData(result.data);
} catch (error) {
setIsError(true);
}
setIsLoading(false);
};
fetchData();
}, [initialUrl, click]);
return [{ data, isLoading, isError }, handleClick];
};
This is working, however, I don't feel this is the correct solution.
I also tried moving the fetchData() out of useEffect and return the fetchData(), and it works too. But according to the React Doc, it says it is recommended to move functions inside the useEffect.
const useDataApi = initialUrl => {
const [data, setData] = useState("");
const [isLoading, setIsLoading] = useState(false);
const [isError, setIsError] = useState(false);
const fetchData = async () => {
setIsError(false);
setIsLoading(true);
try {
const result = await axios(initialUrl);
setData(result.data);
} catch (error) {
setIsError(true);
}
setIsLoading(false);
};
useEffect(() => {
fetchData();
}, []);
return [{ data, isLoading, isError }, fetchData];
};
In addition, for creating these kinds of application, is the way that I am using is fine or there is another correct solution such as not using any useEffects or not create any custom Hook?
Thanks
Not sure if this is correct, but here is my solution.
const useDataApi = initialUrl => {
const [data, setData] = useState("");
const [isLoading, setIsLoading] = useState(false);
const [isError, setIsError] = useState(false);
const doFetch = async () => {
setIsError(false);
setIsLoading(true);
try {
const result = await axios(initialUrl);
setData(result.data);
} catch (error) {
setIsError(true);
}
setIsLoading(false);
};
return [{ data, isLoading, isError }, doFetch];
};
Btw, don't mutate state directly.
const handleClick = () => {
setClick(!click); // don't do this
setClick(prev => !prev); // use this
};
Your implementation is fine. We are also using something similar. Hope you find it useful.
function useApi(promiseFunction, deps, shouldRun=true){
// promisFunction returns promise
const [loading, setLoading] = useState(false)
const [data, setData] = useState(false)
const [error, setError] = useState(false)
const dependencies: any[] = useMemo(()=>{
return [...dependencyArray, shouldRun]
},[...dependencyArray, shouldRun])
const reload = () => {
async function call() {
try {
setError(null)
setLoading(true)
const res = await promiseFunction();
}
catch (error) {
setError(error)
}
finally {
setLoading(false)
}
}
call();
}
useEffect(() => {
if(!shouldRun) return
setResult(null) //no stale data
reload()
}, dependencies)
return {loading, error, data, reload, setState: setData}
}
Below code will provide some idea about how to use it.
function getUsersList(){
return fetch('/users')
}
function getUserDetail(id){
return fetch(`/user/${id}`)
}
const {loading, error, data } = useApi(getUsersList, [], true)
const {loading: userLoading, error: userError, data: userData}
= useApi(()=>getUserDetail(id), [id], true)