Basically i have this array that displays classroom groups and when i press the Button i want so set the variable in my url for my API.
Here is the c
const GroupsScreen = () => {
const [groups, setGroups] = useState([]);
const dispatch = useDispatch();
const [selectedGroup, setSelectedGroup] = useState({});
const routePick = (group) => {
setSelectedGroup(group);
dispatch(routeRequest({id:selectedGroup.id}));
};
useEffect(() => {
getGroupData();
}, []);
return (
<>
<Container>
<CardDeck>
{groups.map((group, index) => {
return (
<Card style={{ width: '18rem' }} key={group.id}>
<Card.Body>
<Card.Title>{group.title}</Card.Title>
<Card.Text>
{group.body}
</Card.Text>
<Button to="/this_group" onClick={() =>routePick(group)} variant="primary">Entrar</Button>
</Card.Body>
</Card>
)
})}
</CardDeck>
</Container>
</>
)
};
And this is the api, it calls the list of users for the selected classroom group:
const { route } = useSelector(state => state.routes);
const getUsersData = async () => {
try {
const response = await fetch("http://lms.bo.be.test/api/courses/" + route + "/users", {
method: 'GET'
});
const { data } = await response.json();
setUsers(data);
} catch (error) {
console.log(error);
}
};
Redux config here:
import { createSlice } from "@reduxjs/toolkit";
const initialState = {
route: null
}
const routesSlice = createSlice({
name: 'routes',
initialState: initialState,
reducers: {
routeSet: (state, action) => {
state.route = action.payload.id;
},
},
});
export default routesSlice.reducer;
const { routeSet } = routesSlice.actions;
export const routeRequest = ( {id} ) => async (dispatch) => {
try {
dispatch(routeSet({id})); //Se pasa el payload como un objeto, sino solo devuelve el primer valor
} catch (e) {
alert(e);
}
};
The problem im facing is that when i click the Button in Card first it passes and undefined and the second time i click it passes the real value (group id).
Any help is welcome. Also i would like to know what you guys think of this way of coding, if there is anything i can improve in this code.
Edit: Setting the state inside useEffect like this fixed the above problem, like this
useEffect(() => {
dispatch(routeRequest({id:selectedGroup.id}));
getGroupData();
}, [selectedGroup]);
The second issue im facing now is probably a newbie one for sure; when Button redirects to the new screen data doesnt get set in state. If i remove the as={Link} property it does set the state but i need to get redirected to new screen because this is where the API shows the list of users.