React Native: Function Undefined - react-native

I am building an app in react native and keep getting an error with a function being defined and cannot seem to figure out how to fix it.
This is the portion of the code that causes the error. It is meant to fetch data from an api using redux and redux-thunk to do it.
componentDidMount() {
this.props.fetchData(
V.sprintf(
"http://timetree.igem.temple.edu/api/pairwise/%s/%s",
this.state.taxonA,
this.state.taxonB
)
);
}
here is the fetchData function that the component uses it is located in an actions folder.
export const fetchData = url => {
return async dispatch => {
dispatch(fetchingRequest());
try {
let response = await fetch(url);
let json = response.json();
dispatch(fetchingSuccess(json));
} catch(error){
dispatch(fetchingFailure(error));
}
}
};
here is how I try to pass it to the component
SearchScreen.propTypes = {
fetchData: PropTypes.func.isRequired,
response: PropTypes.object.isRequired
};

So as I said in comments with propTypes you're not passing anything, you're testing the type of your props. You should import your function and pass it to connect.
import { connect } from 'react-redux';
import { fetchData } from '../actions';
export default connect(mapStateToProps, { fetchData })(App);

the propType define only the types, not the actual value.
if you export the function
export const fetchData
just import it from your component file, and use it:
fetchData(
V.sprintf(
"http://timetree.igem.temple.edu/api/pairwise/%s/%s",
this.state.taxonA,
this.state.taxonB
)
);
without "this.props".

Related

React-Native retrieve API_URL from AsyncStorage and make in accessible in all app (for test purpose)

I am trying to retrieve the API_URL from AsyncStorage and make it accessible in all app, the storing and retrieving (in settings screen) is working fine but when I try to load the data in the App.js using useEffect hook, it returns null. Reloading the app is not working but as soon as I save the App.js (using CTRL-S) it works fine.
Please let me know the correct way to do this.
import React, { useEffect, useState } from "react";
import AsyncStorage from "#react-native-async-storage/async-storage";
export default function App() {
const [hostState, setHostState] = useState(null);
const getAHostInfoAsync = async () => {
const hostInfo = AsyncStorage.getItem('host').then(
setHostState(hostInfo)
).then(
console.log(hostState)
);
};
useEffect(() => {
getAHostInfoAsync();
}, []);
module.exports = {
host: hostState
};
}
and using in another file:
import App from "../../../App";
const API_URL = App.host;
I think your issue is in the way you use async/then. instead of async await.
I am not 100% sure that this is your issue. But if I change my async/await function to use async/then the way you are having it, my IDE says that the variable (hostInfo) might not have been initialised. In any case, I think this is a better syntax than with then.
const getAHostInfoAsync = async () => {
const hostInfo = await AsyncStorage.getItem('host')
setHostState(hostInfo)
console.log(hostState)
};

React-Native Redux error when invoking connect as a function: TypeError: (0, _function.default) is not a function... is an instance of an object

I am trying to use redux-connect in a react-native app. I have connect working in other parts of the app, but I am trying to figure out an issue.
When I import the connect-containing function (NewConnect.js) and invoke it, I get the following error:
TypeError: (0, _NewConnect.default) is not a function. (In '(0, _NewConnect.default)()', '(0, _NewConnect.default)' is an instance of Object)
processAlbums.js
import NewConnect from './NewConnect';
export async function processAlbum(albumtracks, albumartist) {
NewConnect();
...
}
NewConnect.js
import React from 'react';
import {connect} from 'react-redux';
function NewConnect() {
console.log('THIS IS A NEW CONNECT');
}
function mapStateToProps(state) {
return {
theme: state.themeReducer.theme,
duration: state.duration,
};
}
const mapDispatchToProps = dispatch => {
return {
// dispatching plain actions
increment: payload => dispatch({type: 'INCREMENT', payload: payload}),
};
};
export default connect(mapStateToProps, mapDispatchToProps)(NewConnect);

react-redux useSelector() hook not working

I am new to React Native Programming. So, please tell me in detail. thank you.
calling use Selector
I am calling use Selector inside my functional component like this:
import { useDispatch, useSelector } from 'react-redux';
const AddAddressScreen = ({ navigation }) => {
const dispatch = useDispatch();
const data = useSelector(state => state);
console.log(data + "happy Coding");
return (
<View style={styles.container}>
<View>
);
}
export default AddAddressScreen;
My reducer looks like this
case types.API_LOGIN_SUCCESS:
if (action.result.result.mobile_verified === false) {
return {
...state,
onLoad: false,
result: action.result,
status: action.status,
error: null,
navigation: action.navigation.navigate("VerifyMNO")
};
} else {
return {
...state,
onLoad: false,
result: action.result,
status: action.status,
error: null,
navigation: action.navigation.navigate("AddAddress")
};
}
here my mobile number is verified so I move to the address screen.
where I use Use Selector which gives me an error. while I remove above two lines my code runs successfully.
My saga looks like this
export function* watchLoginUserInfo() {
yield takeLatest(types.LOGIN_USER, loginApiSaga)
}
My root saga
import { all, fork } from 'redux-saga/effects';
import { watchLoginUserInfo, } from './authenticationSagas';
function* rootSaga() {
yield all([
watchLoginUserInfo(),
])
}
export default rootSaga;
My Store looks like this
import {createStore, applyMiddleware} from 'redux';
import rootReducer from '../redux/reducers/root-reducer.js'
import createSagaMiddleware from 'redux-saga';
import rootSaga from '../redux/sagas/rootSaga';
const sagaMiddleware = createSagaMiddleware();
const store = createStore(rootReducer, applyMiddleware(sagaMiddleware));
sagaMiddleware.run(rootSaga);
export {store};
when ever I use use Selector hook in my code it gives me the following error.
error 1
error 2, 3, 4
Use the select effect from redux-saga inside of a reducer: https://redux-saga.js.org/docs/api/#selectselector-args
For example const selectedState = yield select(state => state);.
The useSelector hook is for use inside of a function component.
EDIT: since the above doesn't seem to be the issue, I think the issue is that you're calling navigation functions from within your reducer. Reducer code can have no side effects, so you can't call navigation.navigate(...) from within the reducer. This will need to happen in the saga code instead. It might be able to be done in the loginApiSaga or in a dedicated saga that is triggered by API_LOGIN_SUCCESS.

Error: Actions must be plain objects. Use custom middleware for async actions. (React Native)

I am trying to make it so that if an item called code is not set in state with redux, it is called from AsyncStorage and state is set.
import {AsyncStorage} from 'react-native'
import { connect } from 'react-redux';
import {bindActionCreators} from 'redux'
import {handlePhoneNumber, saveCode} from './../../actions/RegistrationActions';
class EnterPhoneNumberScreen extends React.Component {
componentDidMount() {
let code = this.props.registration.code;
console.log("code is", code);
if(code){
// Do nothing
}else{
console.log("in the else");
this.props.getAndSetCode();
}
}
}
const getAndSetCode = () => dispatch => {
console.log("in get and set Code");
AsyncStorage.getItem('code')
.then((data) => {
console.log("data is ", data);
dispatch(saveCode(data));
console.log("in getAndSetCode method, Code is ", data);
})
}
const mapDispatchToProps = dispatch => (
bindActionCreators({
handlePhoneNumber,
getAndSetCode: () => dispatch(getAndSetCode()),
}, dispatch)
);
export default connect(mapStateToProps, mapDispatchToProps)(EnterPhoneNumberScreen);
The console outputs the following:
LOG code is null
LOG in the else
LOG in get and set Code
LOG data is 3tgvgq
LOG in getAndSetCode method, Code is 3tgvgq
I know thunk is properly installed because it is running elsewhere in the application. saveCode is just a normal action:
export const saveCode = code => ({
type: "SAVE_CODE",
payload: code
})
And this error appears in the iphone11 simulator:
How do I fix this?

Integration (Redux with react native)

I am using redux in react-native app. I fetched all values of the category from API & want to pass categoryId to the action.js file.
But I have an issue with passing fetched data to the action.js page. Anyone can give me a solid example of redux for getting data from API and pass it to action#flatlist and #redux
You need to use redux-saga or redux-thunk to handle this scenario.
You can find examples here
Redu-saga
Redux-thunk
You don't need redux-thunk to handler promises you can use async/await and after your promise is solved you can dispatch new data;
import React from 'react';
import { connect } from 'react-redux';
class MyComponent extends React.Component {
constructor() {
this.fetchItems = this.fetchItems.bind(this);
}
async fetchItems() {
const response = await api('api/items');
this.props.dispatch('items', response.data);
}
}
const mapStateToProps = (state) => state;
const mapDispatchToProps = (dispatch) => dispatch;
export default connect(mapStateToProps, mapDispatchToProps)(MyComponent);