React Native can't read Database Firebase - reactjs

I can't read database to insert in 'Text'. I'm using Redux
Json
DiasSemana
|
|__Quarta: "Test Program"
|
|__Quinta: "nothing"
|
|
Class EstudoDia.js I used mapStateToProps, connect and import actions.
import React, { Component } from "react";
import { View, Text } from "react-native";
import { Actions } from "react-native-router-flux";
import { connect } from "react-redux";
import firebase from "firebase";
import { estudoDoDia } from "../actions/AutenticacaoActions";
export class estudoDia extends Component {
componentWillMount() {
//I've tried with 'this.props.quarta' and it didn't work
props.estudoDia(props.quarta);
}
render() {
return (
<View>
<Text>{props.quarta}</Text>
</View>
);
}
}
const mapStateToProps = state => ({
quarta: state.AutenticacaoReducer.quarta
});
export default connect(mapStateToProps, { estudoDoDia })(estudoDia);
types.js
export const MATERIA_DO_DIA = 'materia_do_dia';
ActionReducer.js. I import types and return payload
import { MATERIA_DO_DIA } from "../actions/types";
const INITIAL_STATE = {
quarta: "T.I Program"
};
export default (state = INITIAL_STATE, action) => {
console.log(action);
switch (action.type) {
case MATERIA_DO_DIA:
return { ...state, quarta: action.payload };
default:
return state;
}
};
AutenticacaoActions.js. Used snaphot
import firebase from "firebase";
import { Actions } from "react-native-router-flux";
import { MATERIA_DO_DIA } from "./types";
export const estudoDoDia = quarta => {
return dispatch => {
firebase.database
.ref("/DiasSemana/Quarta")
.once("value")
.then(snapshot => {
quarta = snapshot.val();
dispatch({
type: MATERIA_DO_DIA,
payload: snapshot.val
});
});
};
};
have image in link
enter image description here
thank you if you can help me

I thank you all for your help, in case I discovered that the problem is in the estudoDoDia method in AuthenticationActions.js, I made this change and it worked
export const estudoDoDia = (quarta) => {
return dispatch => {
firebase.database().ref('DiasSemana/Quarta').once('value', function (snapshot) {
console.log(snapshot.val())
quarta = snapshot.toJSON();
dispatch(
{
type: MATERIA_DO_DIA,
payload: quarta
})
})
}
}
Inside once I made it call a function passing the snapshop as a parameter and it worked.
I thank you for your help and thank you all

Related

Err Call Api on redux observable using Axios

I'm trying to learn redux-observables but I seem to be having an issue getting my app to return data. I keep getting the error below and I'm not sure where I'm going wrong or what the error actually means.
I'm trying to learn redux-observables but I seem to be having an issue getting my app to return data. I keep getting the error below and I'm not sure where I'm going wrong or what the error actually means.
I'm trying to learn redux-observables but I seem to be having an issue getting my app to return data. I keep getting the error below and I'm not sure where I'm going wrong or what the error actually means.
I'm trying to learn redux-observables but I seem to be having an issue getting my app to return data. I keep getting the error below and I'm not sure where I'm going wrong or what the error actually means.
ERR: fetchData is not a function
I need help
Contsants
export const FETCH_DATA = "FETCH_DATA";
export const FETCH_DATA_FAIL = "FETCH_DATA_FAIL ";
Action
import { FETCH_DATA, FETCH_DATA_FAIL } from "../contsants/contsants";
export const fetchData = (exampleData = {}) => ({
type: FETCH_DATA,
payload: exampleData
});
export const fetchDataFail = () => ({
type: FETCH_DATA_FAIL
});
Store
import { createStore } from "redux";
import rootReducer from "../Reducer/reducer";
const store = createStore(rootReducer);
export default store;
Reducer
import { FETCH_DATA, FETCH_DATA_FAIL } from "../contsants/contsants";
import { combineReducers } from "redux";
const initialState = {};
export const exampleData = (state = initialState, action: any) => {
switch (action.type) {
case FETCH_DATA:
return action.payload;
case FETCH_DATA_FAIL:
return {};
default:
return state;
}
};
export default combineReducers({
exampleData
});
Epics
import "rxjs";
import axios from "axios";
import { from, of } from "rxjs";
import { mergeMap, map, catchError } from "rxjs/operators";
import { ofType } from "redux-observable";
import { FETCH_DATA } from "../contsants/contsants";
import { fetchData, fetchDataFail } from "../Actions/action"
export const exampleEpic = (action$: any) =>
action$.pipe(
ofType(FETCH_DATA),
mergeMap((action) =>
from(axios.get("jsonplaceholder.typicode.com/todos/1")).pipe(
map((response) => fetchData(response.data)),
catchError(() => of(fetchDataFail()))
)
)
);
App
import { fetchData } from './Actions/action'
import { connect } from "react-redux";
function App(data: any, fetchData: any) {
const handleClickShowsTodos = () => {
fetchData()
console.log(data);
}
return (
<div>
<input type="text" />
<button onClick={handleClickShowsTodos}>ShowsTodo</button>
</div>
);
}
const mapStateToProps = (state: any) => {
return {
data: state
};
};
function mapDispatchToProps(dispatch: any) {
return {
fetchData: () => {
console.log('dispatch')
dispatch(fetchData())
}
};
}
export default connect(mapStateToProps, mapDispatchToProps)(App);

Nextjs - await store.dispatch Cannot read property 'dispatch' of undefined

I'm new to React, Redux and have been following tutorials on the topic. I'm come across a lot of issues that I've been able to resolve but I've come across an issue I can't resolve. I set up store, and can even view it through Chrome's Redux Tools and it show correctly, however when I try and dispatch to the Store, I always get a Cannot read property 'dispatch' of undefined error. I have followed numerous tutorials letter for letter, and am still stuck with the same error message.
Index.Js
import Layout from '../components/layout/Layout';
import Home from '../components/Home';
import { getRooms } from '../redux/actions/roomActions';
import { wrapper } from '../redux/store';
export default function Index() {
return (
<Layout>
<Home />
</Layout>
);
}
export const getServerSideProps = wrapper.getServerSideProps(
async ({ req, store }) => {
await store.dispatch(getRooms(req));
}
);
roomConstants.js
export const ALL_ROOMS_SUCCESS = 'ALL_ROOMS_SUCCESS';
export const ALL_ROOMS_FAIL = 'ALL_ROOMS_FAIL';
export const CLEAR_ERRORS = 'CLEAR_ERRORS';
reducer.js
import { combineReducers } from 'redux';
import { allRoomsReducer } from './roomReducers';
const reducer = combineReducers({
allRooms: allRoomsReducer,
});
export default reducer;
Store.js
import { createStore, applyMiddleware } from 'redux';
import { HYDRATE, createWrapper } from 'next-redux-wrapper';
import thunkMiddleware from 'redux-thunk';
import reducers from './reducers/reducers';
const bindMiddleware = (middleware) => {
if (process.env.NODE_ENV !== 'production') {
const { composeWithDevTools } = require('redux-devtools-extension');
return composeWithDevTools(applyMiddleware(...middleware));
}
return applyMiddleware(...middleware);
};
const reducer = (state, action) => {
if (action.type === HYDRATE) {
const nextState = {
...state,
...action.payload,
};
return nextState;
} else {
return reducers(state, action);
}
};
const initStore = () => {
return createStore(reducer, bindMiddleware([thunkMiddleware]));
};
export const wrapper = createWrapper(initStore);
roomReducer.js
import {
ALL_ROOMS_SUCCESS,
ALL_ROOMS_FAIL,
CLEAR_ERRORS,
} from '../constants/roomConstants';
// All rooms reducer
export const allRoomsReducer = (state = { rooms: [] }, action) => {
switch (action.type) {
case ALL_ROOMS_SUCCESS:
return {
roomsCount: action.payload.roomsCount,
resPerPage: action.payload.resPerPage,
filteredRoomsCount: action.payload.filteredRoomsCount,
rooms: action.payload.rooms,
};
case ALL_ROOMS_FAIL:
return {
error: action.payload,
};
case CLEAR_ERRORS:
return {
...state,
error: null,
};
default:
return state;
}
};
roomAcion.js
import axios from 'axios';
import absoluteUrl from 'next-absolute-url';
import {
ALL_ROOMS_SUCCESS,
ALL_ROOMS_FAIL,
CLEAR_ERRORS,
} from '../constants/roomConstants';
//Clear errors
export const clearErrors = () => async (dispatch) => {
return dispatch({
type: CLEAR_ERRORS,
});
};
// Get all rooms
export const getRooms = (req) => async (dispatch) => {
try {
const { origin } = absoluteUrl(req);
const { data } = await axios.get(`${origin}/api/rooms`);
dispatch({
type: ALL_ROOMS_SUCCESS,
payload: data,
});
} catch (error) {
dispatch({
type: ALL_ROOMS_FAIL,
payload: error.response.data.message,
});
}
};
in index.js, your getServerSideProps function should read this;
export const getServerSideProps = wrapper.getServerSideProps((store) => async ({ req }) => {
await store.dispatch(getRooms(req));})
Use the old version of next-redux-wrapper like 6.0.2

Why can't I call this.state in my redux reducer?

I made a reducer that fetches admins, and I want it to display certain admins when I call it in my reducer but I am getting Undefined.
I am still very new to redux so apologies for my mistakes.
I tried to include all the relevant folders:
App.js
import React, { Component } from 'react';
import { connect } from 'react-redux';
import * as actions from '../store/actions';
class App extends Component {
async componentDidMount() {
fetch(constants.adminUrl + '/admins/data', {
method: 'GET'
}).then((res) => {
return res.json()
}).then(async (res) => {
this.props.setAdminsInColumns(res.admins)
}).catch((error) => {
toast.error(error.message)
})
}
render() {
return (
{/* SOME CODE */}
);
}
}
let app = connect(null, actions)(App);
export default app;
columnsReducer.js
import { FETCH_ADMINS } from '../actions/types'
import { Link } from 'react-router-dom'
import constants from '../../static/global/index'
import React from 'react';
import { toast } from 'react-toastify'
const initialState = {
admins: [],
{
Header: "Responsible",
accessor: "responsibleAdmin",
style: { textAlign: "center" },
// Place where I want to fetch certain admins and get undefined
Cell: props => <span>{props.value && this.state.admins.name ? this.state.admins.find(admin => admin.id === props.value).name : props.value}</span>
}
}
export default function (state = initialState, action) {
switch (action.type) {
case FETCH_ADMINS:
return { ...state, admins: action.admins}
default:
return state
}
}
index.js
import { FETCH_ADMINS } from "./types"
/**
* starts loader for setting admin
*/
export const setAdminsInColumns = (admins) => async dispatch => {
dispatch({ type: FETCH_ADMINS, admins })
}
types.js
export const FETCH_ADMINS = 'fetch_admins'
When I console.log(action.admins) inside the switch case FETCH_ADMINS in the columnsReducer.js file, I can see all the admin information I want, is there a way to make the state global in the columnsReducer.js file so I can read it?
Any help is appreciated!
use mapStateToProps in the connect method. like below
let mapStateToProps = (state)=>{
return {
admins :[yourcolumnsReducer].admins
}
}
let app = connect(mapStateToProps, actions)(App);
//you can use this.props.admins inside your component
MapStateToProps reference

Re-rendering the component after dispatching action from non-component JS file

I'm dispatching the action from a non-component JS (utils/index.js) file using store.dispatch(), but after the reducer state change, the component in which that reducer state is connected using mapStateToProps is not being re-rendered,
What am i doing wrong?
Any help would be appreciated
Thanks in advance
I tried searching through out and i went to all the questions and articles which are dispatching the action from a component file.
All the related files
/store/index.js
import { createStore } from "redux";
import rootReducer from "reducers";
store = createStore(rootReducer);
/utils/index.js
import store from './store';
import { toggleShowAlert } from "reducers/alert";
export const customAlert = msg => {
store.dispatch(toggleShowAlert(msg));
}
/views/Nav/index.js
import React, { Component } from 'react';
import { connect } from 'react-redux';
class Nav extends Component {
render() {
....
// component code
....
}
}
const mapStateToProps = state => {
return {
showAlert: state.alert.showAlert
}
}
export default connect(mapStateToProps)(Nav);
/reducer/alert.js
const TOGGLE_SHOW_ALERT = "TOGGLE_SHOW_ALERT";
export const toggleShowAlert = msg => {
return dispatch => {
dispatch({
type: TOGGLE_SHOW_ALERT,
msg
});
};
};
const initialState = {
showAlert: false,
alertMsg: ""
};
const reducer = (state = initialState, action) => {
switch (action.type) {
case TOGGLE_SHOW_ALERT:
return {
...state,
showAlert: !state.showAlert,
alertMsg: state.showAlert ? "" : action.msg
};
default:
return { ...state };
}
}
export default reducer;
another reducer from which that customAlert is being called
/reducers/user.js
import { customAlert } from 'utils';
...other codes...
export const updateAgeGender = (userId, age, gender) => {
return dispatch => {
dispatch(updateButtonLoading());
callAPI("post", `${COMM_BE_URL}/users/update-age-gender`, {
userId,
age,
gender
})
.then(res => {
if (res.status === "SUCCESS") {
dispatch(updateAgeGenderAction(age, gender));
customAlert("Your info has been updated, now u can join");
}
})
.catch(err => {
console.log(err);
dispatch(updateError(SERVER_ERROR_MSG));
});
};
};
After change of showAlert, the Nav Component should re-render, but it's not happening

Redux doesn't fetch data from API request

I'm new to React/Redux. I'm making an app using an API but the code doesn't work. When I run the code it says "this.props.recipes.map is not a function" and doesn't render anything.
If I change payload to: "payload: response.data.recipes" then the error changes to "Given action "FETCH_RECIPE", reducer "recipes" returned undefined." but no errors on screen (only in console). I thought writing "(state = [], action)" would solve the problem but it seems not. What's the problem and how do I fix this error?
Action Creator
import recipe from '../apis/recipe';
export const fetchRecipe = () => async dispatch => {
const response = await recipe.get('');
dispatch({ type: 'FETCH_RECIPE', payload: response.data })
};
Reducer
import { combineReducers } from 'redux';
const recipeReducer = (state = [], action) => {
switch(action.type) {
case 'FETCH_RECIPE':
return action.payload;
default:
return state;
}
};
export default combineReducers({
recipes: recipeReducer
});
import React from 'react';
import { connect } from 'react-redux';
import { fetchRecipe } from '../actions';
class Recipe extends React.Component {
componentDidMount() {
this.props.fetchRecipe();
console.log("This doesn't work", this.props.recipes)
}
renderList() {
return this.props.recipes.map(recipe => {
return (
<div>
<p>{recipe.publisher}</p>
</div>
)
})
}
render() {
console.log("First loaded: empty, second time: data fetched", this.props.recipes)
return (
<div>
{this.renderList()}
</div>
);
}
}
const mapStateToProps = (state) => {
return { recipes: state.recipes }
};
export default connect(mapStateToProps,{
fetchRecipe
})(Recipe);
API Request
import axios from 'axios';
import { key } from './config';
export default axios.create({
baseURL: `https://cors-anywhere.herokuapp.com/https://www.food2fork.com/api/search?key=${key}&q=pizza`
});

Resources