I want the function FetchAll.getAll() to be called from the AddTracker.addOne() method
Here's the UI component I'm exporting called FetchAll with the method called getAll
import React, { Component } from "react";
export default class FetchAll extends Component {
state = {
loading: true,
trackers: null,
};
getAll = async () => {
let res = await fetch("http://localhost:8181/trackers");
const json = await res.json();
this.setState({ trackers: json.data, loading: false });
};
componentDidMount() {
this.getAll();
}
render() {
return (
<>
{this.props.render(
this.state.loading,
this.state.trackers,
this.getAll
)}
</>
);
}
}
The Navbar Component that's importing FetchAll then passing in the getAll prop to the AssTracker component
import React from "react";
import { AddTracker, FetchAll } from "./index";
import { Navbar} from "react-bootstrap";
export default function NavComponent(props) {
return (
<>
<Navbar >
<FetchAll
render={(loading, trackers, getAll) => {
return <AddTracker getAll={getAll} />;
}}
/>
</Navbar>
</>
);
}
The AddTracker component where I want the props.getAll function to be called
import React, { useState } from "react";
import { Form, FormControl, Button } from "react-bootstrap";
const DB = "http://localhost:8181/trackers";
export default function AddTracker(props) {
function formClick(e) {
e.preventDefault();
let dataObj = { url: formData };
const addOne = async () => {
let res = await fetch(DB, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(dataObj),
}).catch((err) => console.log(err));
const text = await res.text();
console.log(text);
return text;
};
const runFirst = async () => {
await addOne();
props.getAll(); // nothing happens
console.log(props.getAll()); // Promise {<pending>}
console.log(props); // {getAll: f}
};
runFirst();
}
const [formData, setFormData] = useState();
return (
<>
<Form inline>
<FormControl
type="text"
onChange={(e) => {
setFormData(e.target.value);
}}
/>
<Button variant="primary" onClick={(e) => formClick(e)}>
Add Tracker
</Button>
</Form>
</>
);
}
I can not get props.getAll() to be called inside of AddTracker. I've tried calling it directly inside of addOne, I've tried extracting it to a constant in the outer scope per vscode. I'm not sure what else to try.I've got it working in another component which makes it all the more perplexing.
Any help would be appreciated.
Thanks!
Itʼs not clear from your question what problem you are encountering, but I notice that your addOne() function has a props parameter that shadows the props of the AddTracker component. So Iʼm guessing props.getAll is undefined where you try to call it because getAll() is a property of the outer (shadowed) props.
The eslint no-shadow rule is helpful for making this kind of problem more immediately obvious.
Related
I am a newbie in React and Next JS, I want to set initial auth user data on initial load from the __app.js. But using dispatch throwing error "Invalid hook call". I know according to docs calling hooks in render function is wrong. but I am looking for an alternate solution to this.
How I can set auth data one-time so that will be available for all the pages and components.
I am including my code below.
/contexts/app.js
import { useReducer, useContext, createContext } from 'react'
const AppStateContext = createContext()
const AppDispatchContext = createContext()
const reducer = (state, action) => {
switch (action.type) {
case 'SET_AUTH': {
return state = action.payload
}
default: {
throw new Error(`Unknown action: ${action.type}`)
}
}
}
export const AppProvider = ({ children }) => {
const [state, dispatch] = useReducer(reducer, {})
return (
<AppDispatchContext.Provider value={dispatch}>
<AppStateContext.Provider value={state}>
{children}
</AppStateContext.Provider>
</AppDispatchContext.Provider>
)
}
export const useAuth = () => useContext(AppStateContext)
export const useDispatchAuth = () => useContext(AppDispatchContext)
/_app.js
import 'bootstrap/dist/css/bootstrap.min.css'
import '../styles/globals.css'
import App from 'next/app'
import Layout from '../components/Layout'
import { mutate } from 'swr'
import { getUser } from '../requests/userApi'
import { AppProvider, useDispatchAuth } from '../contexts/app'
class MyApp extends App {
render() {
const dispatchAuth = useDispatchAuth()
const { Component, pageProps, props } = this.props
// Set initial user data
const setInitialUserData = async () => {
if (props.isServer) {
const initialData = {
loading: false,
loggedIn: (props.user) ? true : false,
user: props.user
}
const auth = await mutate('api-user', initialData, false)
dispatchAuth({
type: 'SET_AUTH',
payload: auth
})
}
}
//----------------------
// Set initial user data
setInitialUserData()
//----------------------
return (
<AppProvider>
<Layout>
<Component {...pageProps} />
</Layout>
</AppProvider>
)
}
}
MyApp.getInitialProps = async (appContext) => {
let isServer = (appContext.ctx.req) ? true : false
let user = null
let userTypes = {}
// Get user server side
if (isServer) {
await getUser()
.then(response => {
let data = response.data
if (data.status == true) {
// Set user
user = data.data.user
userTypes = data.data.user_types
//---------
}
})
.catch(error => {
//
})
}
//---------------------
return {
props: {
user,
userTypes,
isServer
}
}
}
export default MyApp
I believe this is the intended use of the useEffect hook with an empty array as its second argument:
https://reactjs.org/docs/hooks-effect.html
import {useEffect} from 'react'
class MyApp extends App {
useEffect(()=> {
setInitialUserData()
},[])
render() {
...
}
}
I'm quite new to React Hooks/Context so I'd appreciate some help. Please don' t jump on me with your sharp teeth. I Checked other solutions and some ways i've done this before but can't seem to get it here with the 'pick from the list' way.
SUMMARY
I need to get the municipios list of names inside of my const 'allMunicipios'(array of objects) inside of my Search.js and then display a card with some data from the chosen municipio.
TASK
Get the data from eltiempo-net REST API.
Use Combobox async element from Elastic UI to choose from list of municipios.
Display Card (from elastic UI too) with some info of chosen municipio.
It has to be done with function components / hooks. No classes.
I'd please appreciate any help.
WHAT I'VE DONE
I've created my reducer, context and types files in a context folder to fecth all data with those and then access data from the component.
I've created my Search.js file. Then imported Search.js in App.js.
I've accesed the REST API and now have it in my Search.js
PROBLEM
Somehow I'm not beeing able to iterate through the data i got.
Basically i need to push the municipios.NOMBRE from api to the array const allMunicipios in my search.js component. But when i console log it it gives me undefined. Can;t figure out why.
I'll share down here the relevant code/components. Thanks a lot for whoever takes the time.
municipiosReducer.js
import {
SEARCH_MUNICIPIOS,
CLEAR_MUNICIPIOS,
GET_MUNICIPIO,
GET_WEATHER,
} from "./types";
export default (state, action) => {
switch (action.type) {
case SEARCH_MUNICIPIOS:
return {
...state,
municipios: action.payload,
};
case GET_MUNICIPIO:
return {
...state,
municipio: action.payload,
};
case CLEAR_MUNICIPIOS:
return {
...state,
municipios: [],
};
case GET_WEATHER: {
return {
...state,
weather: action.payload,
};
}
default:
return state;
}
};
municipiosContext.js
import { createContext } from "react";
const municipiosContext = createContext();
export default municipiosContext;
MunicipiosState.js
import React, { createContext, useReducer, Component } from "react";
import axios from "axios";
import MunicipiosContext from "./municipiosContext";
import MunicipiosReducer from "./municipiosReducer";
import {
SEARCH_MUNICIPIOS,
CLEAR_MUNICIPIOS,
GET_MUNICIPIO,
GET_WEATHER,
} from "./types";
const MunicipiosState = (props) => {
const initialState = {
municipios: [],
municipio: {},
};
const [state, dispatch] = useReducer(MunicipiosReducer, initialState);
//Search municipios
//In arrow functions 'async' goes before the parameter.
const searchMunicipios = async () => {
const res = await axios.get(
`https://www.el-tiempo.net/api/json/v2/provincias/08/municipios`
// 08 means barcelona province. This should give me the list of all its municipios
);
dispatch({
type: SEARCH_MUNICIPIOS,
payload: res.data.municipios,
});
};
//Get Municipio
const getMunicipio = async (municipio) => {
const res = await axios.get(
`https://www.el-tiempo.net/api/json/v2/provincias/08/municipios/${municipio.CODIGOINE}`
//CODIGOINE is in this REST API kind of the ID for each municipio.
//I intent to use this later to get the weather conditions from each municipio.
);
dispatch({ type: GET_MUNICIPIO, payload: res.municipio });
};
const dataMunicipiosArray = [searchMunicipios];
//Clear Municipios
const clearMunicipios = () => {
dispatch({ type: CLEAR_MUNICIPIOS });
};
return (
<MunicipiosContext.Provider
value={{
municipios: state.municipios,
municipio: state.municipio,
searchMunicipios,
getMunicipio,
clearMunicipios,
dataMunicipiosArray,
}}
>
{props.children}
</MunicipiosContext.Provider>
);
};
export default MunicipiosState;
Search.js
import "#elastic/eui/dist/eui_theme_light.css";
import "#babel/polyfill";
import MunicipiosContext from "../contexts/municipiosContext";
import MunicipiosState from "../contexts/MunicipiosState";
import { EuiComboBox, EuiText } from "#elastic/eui";
import React, { useState, useEffect, useCallback, useContext } from "react";
const Search = () => {
const municipiosContext = useContext(MunicipiosContext);
const { searchMunicipios, municipios } = MunicipiosState;
useEffect(() => {
return municipiosContext.searchMunicipios();
}, []);
const municipiosFromContext = municipiosContext.municipios;
const bringOneMunicipio = municipiosContext.municipios[0];
let municipiosNames = municipiosFromContext.map((municipio) => {
return { label: `${municipio.NOMBRE}` };
});
console.log(`municipiosFromContext`, municipiosFromContext);
console.log(`const bringOneMunicipio:`, bringOneMunicipio);
console.log(`municipiosNames:`, municipiosNames);
const allMunicipios = [
{ label: "santcugat" },
{ label: "BARCELONETA" },
{ label: "BARCE" },
];
const [selectedOptions, setSelected] = useState([]);
const [isLoading, setLoading] = useState(false);
const [options, setOptions] = useState([]);
let searchTimeout;
const onChange = (selectedOptions) => {
setSelected(selectedOptions);
};
// combo-box
const onSearchChange = useCallback((searchValue) => {
setLoading(true);
setOptions([]);
clearTimeout(searchTimeout);
// eslint-disable-next-line react-hooks/exhaustive-deps
searchTimeout = setTimeout(() => {
// Simulate a remotely-executed search.
setLoading(false);
setOptions(
municipiosNames.filter((option) =>
option.label.toLowerCase().includes(searchValue.toLowerCase())
)
);
}, 1200);
}, []);
useEffect(() => {
// Simulate initial load.
onSearchChange("");
}, [onSearchChange]);
return (
<div>
<EuiComboBox
placeholder="Search asynchronously"
async
options={options}
selectedOptions={selectedOptions}
isLoading={isLoading}
onChange={onChange}
onSearchChange={onSearchChange}
/>
<button>Lista de municipios</button>
</div>
);
};
export default Search;
also the
Home.js
import React, { useState } from "react";
import { EuiComboBox, EuiText } from "#elastic/eui";
// import { DisplayToggles } from "../form_controls/display_toggles";
import "#babel/polyfill";
import "#elastic/eui/dist/eui_theme_light.css";
import Search from "./Search";
import MunicipioCard from "./MunicipioCard";
const Home = () => {
return (
<div>
<EuiText grow={false}>
<h1>Clima en la provincia de Barcelona</h1>
<h2>Por favor seleccione un municipio</h2>
</EuiText>
<Search />
<MunicipioCard />
</div>
);
};
export default Home;
App.js
import "#babel/polyfill";
import "#elastic/eui/dist/eui_theme_light.css";
import { EuiText } from "#elastic/eui";
import React from "react";
import Home from "./components/Home";
import MunicipiosState from "./contexts/MunicipiosState";
import "./App.css";
function App() {
return (
<MunicipiosState>
<div className="App">
<EuiText>
<h1>App Component h1</h1>
</EuiText>
<Home />
</div>
</MunicipiosState>
);
}
export default App;
You are using forEach and assigning the returned value to a variable, however forEach doesn't return anything. You should instead use map
let municipiosNames = municipiosFromContext.map((municipio) => {
return `label: ${municipio.NOMBRE}`;
});
As per your comment:
you data is loaded asynchronously, so it won't be available on first render and since functional components depend on closures, you onSearchChange function takes the value from the closure at the time of creation and even if you have a setTimeout within it the updated value won't reflect
The solution here is to add municipiosFromContext as a dependency to useEffect
const onSearchChange = useCallback((searchValue) => {
setLoading(true);
setOptions([]);
clearTimeout(searchTimeout);
// eslint-disable-next-line react-hooks/exhaustive-deps
searchTimeout = setTimeout(() => {
// Simulate a remotely-executed search.
setLoading(false);
setOptions(
municipiosNames.filter((option) =>
option.label.toLowerCase().includes(searchValue.toLowerCase())
)
);
}, 1200);
}, [municipiosFromContext]);
useEffect(() => {
// Simulate initial load.
onSearchChange("");
}, [onSearchChange]);
I am making auth component using react-native.
And the code below sends to 'MainTab' of 'this.props.navigation' depends on the result of axios.
<TouchableOpacity onPress={this.handleSubmit}>
<Text>Save</Text>
</TouchableOpacity>
handleSubmit = () => {
const result = await axios.post(
'http://192.0.0.1:4000/clients',
users
);
if (result.data.success) {
return this.props.navigation.navigate('MainTab');
}
return false
};
But I want to use handleSubmit at an other 'js' file to avoid doing repeatedly.
Thus, I edit a code like below.
import { saveSettings } from '../../storage/settingsStorage'
handleSubmit(): void {
saveSettings(this.state);
}
// in 'settingsStorage.js'
export const saveSettings = async users => {
try {
const result = await axios.post(
'http://192.0.0.1:4000/clients/token',
users
);
if (result.data.success) {
return this.props.navigation.navigate('MainTab');
}
return false
} catch (e) {
console.log(e);
}
};
And in this case, I know 'this.props' can't be passed in normal Js file without passing props. But I don't know how can I pass the props?
Thank you so much for reading this.
Based on your description I think you can just add a second parameter to saveSettings and pass the navigation object through:
import { saveSettings } from '../../storage/settingsStorage'
handleSubmit(): void {
saveSettings(this.state, this.props.navigation);
}
// in 'settingsStorage.js'
export const saveSettings = async (users, navigation) => {
try {
const result = await axios.post(
'http://192.0.0.1:4000/clients/token',
users
);
if (result.data.success) {
return navigation.navigate('MainTab');
}
return false
} catch (e) {
console.log(e);
}
};
Instead of passing navigation prop you can use a technique Navigating without the navigation prop as described in official site .
App.js
import { createStackNavigator, createAppContainer } from 'react-navigation';
import NavigationService from './NavigationService';
const TopLevelNavigator = createStackNavigator({
/* ... */
});
const AppContainer = createAppContainer(TopLevelNavigator);
export default class App extends React.Component {
// ...
render() {
return (
<AppContainer
ref={navigatorRef => {
NavigationService.setTopLevelNavigator(navigatorRef);
}}
/>
);
}
}
we define NavigationService which is a simple module with functions that dispatch user-defined navigation actions.
/ NavigationService.js
import { NavigationActions } from 'react-navigation';
let _navigator;
function setTopLevelNavigator(navigatorRef) {
_navigator = navigatorRef;
}
function navigate(routeName, params) {
_navigator.dispatch(
NavigationActions.navigate({
routeName,
params,
})
);
}
// add other navigation functions that you need and export them
export default {
navigate,
setTopLevelNavigator,
};
Now use it every where without navigation prop
// any js module
import NavigationService from 'path-to-NavigationService.js';
// ...
NavigationService.navigate('MainTab');
WebContext.js
import React, { createContext, Component } from 'react';
export const WebContext = createContext();
class WebContextProvider extends Component {
state = {
inputAmount: 1,
};
render() {
return <WebContext.Provider value={{ ...this.state }}>{this.props.children}</WebContext.Provider>;
}
}
export default WebContextProvider;
App.js
const App = () => {
return (
<WebContextProvider>
<UpdateBtn />
</WebContextProvider>
);
};
export default App;
UpdateBtn.js
const UpdateBtn = () => {
return (
<Div>
<Button onClick={} />
</Div>
);
};
export default UpdateBtn;
How do I update the inputAmount state present in WebContext.js on button click in UpdateBtn.js? App.js is the parent component for UpdateBtn.js Also, How can I convert the WebContext.js into a functional component?
You should pass the function in Provider which you can call to update the value:
WebContext.js
import React, { createContext, Component } from 'react';
export const WebContext = createContext();
class WebContextProvider extends Component {
state = {
inputAmount: 1,
};
render() {
return (
<WebContext.Provider
value={{
data: ...this.state, // all data now in context.data field
update: () => { // we added this callback
this.setState((state) => ({
inputAmount: state.inputAmount + 1,
}));
},
}}
>
{this.props.children}
</WebContext.Provider>
);
}
}
export default WebContextProvider;
App.js
const App = () => {
return (
<WebContextProvider>
<UpdateBtn />
</WebContextProvider>
);
};
export default App;
UpdateBtn.js
const UpdateBtn = () => {
const context = useContext(WebContext); // we use hook to get context value
return (
<Div>
<Button onClick={context.update} />
</Div>
);
};
export default UpdateBtn;
or
const UpdateBtn = () => {
// or we can use Consumer to get context value
return (
<Div>
<WebContext.Consumer>
{context => <Button onClick={context.update} />}
</WebContext.Consumer>
</Div>
);
};
export default UpdateBtn;
An alternative approach might be to use a reducer to update your state. For example:
export const initialState = {
inputValue: 1
}
export function reducer(state, action) {
const { type, payload } = action;
switch (type) {
case 'updateInputValue': {
return { ...state, inputValue: payload };
}
default: return state;
}
}
Import those into your provider file:
import { initialState, reducer } from './reducer';
and use useReducer to create a store:
export function WebContextProvider({ children }) {
const store = useReducer(reducer, initialState);
return (
<WebContext.Provider value={store}>
{children}
</WebContext.Provider>
);
}
You can then import the context into the component that needs it and use useContext to get at the state and dispatch method. On the click of the button you can dispatch a new value to the store to update inputValue.
export default function UpdateButton() {
const [ { inputValue }, dispatch ] = useContext(WebContext);
function handleClick(e) {
dispatch({
type: 'updateInputValue',
payload: inputValue + 1
});
}
return (
<div>
<div>{inputValue}</div>
<button onClick={handleClick}>Click</button>
</div>
);
};
I've created a full demo to show you how it works in harmony.
I have created a search box inside component. So I am calling onchange function outside in parent App.js. Now I am trying to dispatch that function if I type anything in search box but I can't access that function outside my class.
How to dispatch my function?
Please find my source code below:
import React, {Component} from "react";
import {connect} from "react-redux";
import { User } from "../components/User";
import { Main } from "../components/Main";
import Data from "../components/Data";
import MovieListing from '../components/MovieListing';
import Header from '../components/Header'
import { setName, getApiData } from "../actions/userActions";
import {apiFetch} from "../actions/dataActions"
import {searchFetch} from "../actions/searchActions"
class App extends Component {
constructor(props){
super(props)
this.searchQuery = this.searchQuery.bind(this);
}
searchQuery( query ) {
}
render() {
let dataSet=this.props.data.data.results;
let imagePath = []
let original_title = []
let release_date = []
let original_language = []
if(dataSet){
dataSet.forEach(function (value, key) {
imagePath.push(<Data key={key} imagePath={value.backdrop_path} release_date={value.release_date} original_title={value.original_title} original_language={value.original_language} />)
original_title.push(value.original_title)
})
return(
<div className="wrapper">
<Header searchQuery = { this.searchQuery } />
<div className="movies-listing">
<div className="container">
<MovieListing imagePath={imagePath} release_date={release_date} original_title={original_title} original_language={original_language} />
</div>
</div>
</div>
)
}else{
return(
<div className="middle-loader">
<h1>Loading</h1>
</div>
)
}
// console.log("this.props",this.props);
}
}
const mapStateToProps = (state) => {
return {
user: state.user,
math: state.math,
data: state.data,
searchData: state.searchData
};
};
const mapDispatchToProps = (dispatch) => {
return dispatch(apiFetch()), {searchQuery: (query) => {searchFetch(query)}}
};
export default connect(mapStateToProps, mapDispatchToProps)(App);
Here I can't access that {searchQuery: (query) => {searchFetch(query)}} because of not accessible that function outside class.
HELP WOULD BE APPRECIATED!!
mapDispatchToProps takes/passes the dispatch function and then return searchQuery function as a prop.
const mapDispatchToProps = (dispatch) => {
return {
searchQuery: (query) => { dispatch(searchFetch(query)) }
}
};
Then in the Header component pass the searchQuery prop
<Header searchQuery={ this.props.searchQuery } />