how to show a success message after navigation and when opening new screen? - react-navigation

after login success i need to show a message that the operation was successful on the nextpage
thanks for help
import {showMessage} from "react-native-flash-message";
import { NavigationContainer ,useFocusEffect} from '#react-navigation/native';
const MainScreen = ({ route, navigation }) => {
const { userId, email } = route.params;
useFocusEffect(
React.useCallback(() => {
showMessage({
message: "Welcome mr "+email,
type: "success",
});
}, [])
);
return(
<View>
<Text>aaaa</Text>
</View>
)
}
export default MainScreen;

You can use useEffect for this :-
import React, {useEffect} from 'react';
useEffect(() => {
showMessage({
message: "Welcome mr "+email,
type: "success",
});
}, []);

Related

Network Request Failed Error React Native, using Flask Python as BackEnd

Using postman the backend seems to be getting the correct data back but when I throw it into a fetch the components are not re-rendering the state and also giving me a yellow error, of Network Request Failed.
The backend is made of Flask Python, and the FrontEnd is using Expo CLI with an android emulator, I looked up previous issues and found some saying the emulator and the machine are not connected, I fixed that issue by doing a remote/local ip ex: 192.168.1.... but it's still returning a network request failed.
import React, { useEffect, useState } from "react";
import { ScrollView, View, TouchableOpacity, Text } from "react-native";
import { connect } from "react-redux";
import * as actions from "../src/actions";
import EarningsBar from "./EarningsBar";
const DayCalendar = (props) => {
const [isLoaded, setisLoaded] = useState(false);
useEffect(() => {
props.loadStock("daily");
if (Object.keys(props.dailyStocks).length > 0) {
setisLoaded(true);
console.log(props.dailyStocks);
}
}, []);
return (
<ScrollView nestedScrollEnabled={true}>
{isLoaded === true &&
props.dailyStocks.time.map(
({ companyshortname, epsactual, epsestimate, ticker }, index) => {
return (
<EarningsBar
key={index}
companyName={companyshortname}
companyAbbrev={ticker}
companyEPS={epsestimate}
companyRev={"$3.28"}
companyActualEPS={epsactual}
companyActualRES={"$5.66"}
companyGrowthEPS={"103.3%"}
companyGrowthRev={"83.8%"}
arrow={"good"}
/>
);
}
)}
</ScrollView>
);
};
const mapStateToProps = (state) => {
return {
dailyStocks: state.calendar.daily,
};
};
export default connect(mapStateToProps, actions)(DayCalendar);
This is the day calendar Component
Here is the action function
export const loadStock = (stock) => {
return (dispatch) => {
try {
fetch(`http://192.168.1.13:3000/${stock}stock`)
.then((response) => {
return response.json();
})
.then((data) => {
dispatch({ type: "LOAD_STOCKS", payload: { stock, data } });
});
} catch (error) {
console.log(error);
}
};
};
My reducer states/and switch cases
export const initialLoginState = {
users: [],
searchedStocks: [],
calendar: {
daily: [],
weekly: [],
monthly: [],
},
stocks: [],
searchTerm: null,
isLoading: true,
user_id: null,
username: null,
password: null,
confirmPassword: null,
email: null,
birthdate: null,
question: null,
answer: null,
userToken: null,
isValidUser: true,
isValidPassword: true,
};
export default (prevState = initialLoginState, action) => {
switch (action.type) {
case "LOAD_STOCKS":
return {
...prevState,
calendar: {
[action.payload.prop]: action.payload.value,
},
};
default:
return {
...prevState,
};
}
};
If you would like to see the full repo I have linked it down below. I have been trying to figure out the issue for quite some time now and I just need a new perspective on it, thank you so much for your time.
https://github.com/JayPankajPatel/EarningsWhisper
Open CMD and run ipconfig, then copy your ip address there
In your flask code, let say app.py
Change app.run() to
app.run(host=your ip address)

What should I expect for navigate buttons in react using react-testing library

I don't understand what should I expect for navigate button in the below code. can any one help me with this. Thank you.
code:
import react from 'react';
const HomeButton = (props) => {
const history = props.history;
function handleClick() {
history.push("/home");
}
return (
<button type="button" onClick={handleClick} data-testid="goToHome">
Go home
</button>
);
}
export default HomeButton;
This is the test code I have been trying for the above component
import React from 'react';
import { render, screen, fireEvent } from '#testing-library/react';
import GoToHome from '../GoToHome';
describe('Read only text', () => {
const history = createMemoryHistory();
it('text came from props', () => {
const { container } = render(<GoToHome history={history} />);
const goToHome = screen.getByTestId('goToHome')
fireEvent.click(goToHome, jest.fn())
expect(container).
});
});
you can check my passing the history as a prop with push property assigned to jest.fn as mock function and check if it is getting called when you press to navigate button
describe('Read only text', () => {
const mockPush = jest.fn()
const history = {
push: mockPush()
}
it('text came from props', () => {
const { container } = render(<GoToHome history={history} />);
const goToHome = screen.getByTestId('goToHome')
fireEvent.click(goToHome)
expect(mockPush ).toBeCalled()
});
});

How to redirect another router in Vue3 ? (used next.router in Laravel 8 with vue3)

It does not redirect after successfully logged in.
getting a console error TypeError: Cannot read property 'push' of undefine
Here my code.
I'm creating SPA in vue3 with Laravel 8.
import { ref } from "vue";
import { useRoute } from "vue-router";
export default {
setup() {
const form = ref(
{
email: "hudson.vilma#example.net",
password: "password",
isLoading: false,
},
);
const user = ref("");
function login() {
axios.get('/sanctum/csrf-cookie').then(response => {
axios.post('/login', this.form).then(response => {
this.$router.push('/dashboard')
// useRoute.push('/dashboard');
// this.$router.push({ name: "Dashboard" });
}).catch(error => console.log(error)); // credentials didn't match
});
}
return { form, login, user , useRoute};
},
};
</script>
in app.js instant of vue &
require('./bootstrap');
import { createApp } from "vue";
import App from "./view/App.vue";
import router from "./router";
const app = createApp(App);
app.use(router);
app.mount("#app");
Try to use useRouter instead of useRoute and instantiate it like const router =useRouter() in setup function:
import { ref } from "vue";
import { useRouter } from "vue-router";
export default {
setup() {
const router =useRouter()
const form = ref(
{
email: "hudson.vilma#example.net",
password: "password",
isLoading: false,
},
);
const user = ref("");
function login() {
axios.get('/sanctum/csrf-cookie').then(response => {
axios.post('/login', this.form).then(response => {
router.push('/dashboard')
}).catch(error => console.log(error)); // credentials didn't match
});
}
return { form, login, user ,};
},
};
</script>
Note that this couldn't be used in composition API.
You are using this.$router.push('/dashboard') in setup(). This cannot be used in setup(). Instead you can use...
router.push('/dashboard')

BeforeUpload do not trigger upload on promise resolved

Using React, and antd
I have the following code in my component:
<Upload
action={HttpService.getBaseUrl(`post_import_csv`, HttpService.AuditcoreAPIBasePath)}
headers={{"Authorization": `Bearer ${AuthHelper.getAuthKey()}`}}
showUploadList={false}
multiple={false}
beforeUpload={(file: RcFile): PromiseLike<any> => {
this.setCSV(file);
return new Promise((resolve) => {
this.state.requestUpload.pipe(take(1)).subscribe(() => {
resolve(file);
console.log('resolved')
});
})
}}></Upload>
Basically I want my beforeUpload to wait for the user to click on a button before uploading the file. I did so by returning a Promise and waiting for a rxjs Suject that is triggered on button click to resolve the promise. Pretty much following the doc
Here is the button code :
<Button
onClick={(e): void => {
this.state.requestUpload.next(true);
}}
>
Upload
</Button>
It works nice, but the file is never uploaded, I do see my log resolved but there is no trace of network call in my console.
I fixed using this approach which is cleaner :
https://codesandbox.io/s/xvkj90rwkz
Basically, having a custom function that handle upload. It doesn't explain why my tricky solution was not working, but I got it working.
import React from 'react';
import ReactDOM from 'react-dom';
import 'antd/dist/antd.css';
import './index.css';
import { Upload, Button, Icon, message } from 'antd';
import reqwest from 'reqwest';
class Demo extends React.Component {
state = {
fileList: [],
uploading: false,
};
handleUpload = () => {
const { fileList } = this.state;
const formData = new FormData();
fileList.forEach(file => {
formData.append('files[]', file);
});
this.setState({
uploading: true,
});
// You can use any AJAX library you like
reqwest({
url: 'https://www.mocky.io/v2/5cc8019d300000980a055e76',
method: 'post',
processData: false,
data: formData,
success: () => {
this.setState({
fileList: [],
uploading: false,
});
message.success('upload successfully.');
},
error: () => {
this.setState({
uploading: false,
});
message.error('upload failed.');
},
});
};
render() {
const { uploading, fileList } = this.state;
const props = {
onRemove: file => {
this.setState(state => {
const index = state.fileList.indexOf(file);
const newFileList = state.fileList.slice();
newFileList.splice(index, 1);
return {
fileList: newFileList,
};
});
},
beforeUpload: file => {
this.setState(state => ({
fileList: [...state.fileList, file],
}));
return false;
},
fileList,
};
return (
<div>
<Upload {...props}>
<Button>
<Icon type="upload" /> Select File
</Button>
</Upload>
<Button
type="primary"
onClick={this.handleUpload}
disabled={fileList.length === 0}
loading={uploading}
style={{ marginTop: 16 }}
>
{uploading ? 'Uploading' : 'Start Upload'}
</Button>
</div>
);
}
}
ReactDOM.render(<Demo />, document.getElementById('container'));

Fetch request in React: How do I Map through JSON array of objects, setState() & append?

This API returns a JSON array of objects, but I'm having trouble with setState and appending. Most documentation covers JSON objects with keys. The error I get from my renderItems() func is:
ItemsList.js:76 Uncaught TypeError: Cannot read property 'map' of undefined
in ItemsList.js
import React, { Component } from "react";
import NewSingleItem from './NewSingleItem';
import { findDOMNode } from 'react-dom';
const title_URL = "https://www.healthcare.gov/api/index.json";
class ItemsList extends Component {
constructor(props) {
super(props);
this.state = {
// error: null,
// isLoaded: false,
title: [],
url: [],
descrip: []
};
}
componentDidMount() {
fetch(title_URL)
.then(response => {
return response.json();
})
.then((data) => {
for (let i = 0; i < data.length; i++) {
this.setState({
title: data[i].title,
url: data[i].url,
descrip: data[i].bite,
});
console.log(data[i])
}
})
.catch(error => console.log(error));
}
renderItems() {
return this.state.title.map(item => {
<NewSingleItem key={item.title} item={item.title} />;
});
}
render() {
return <ul>{this.renderItems()}</ul>;
}
}
export default ItemsList;
Above, I'm trying to map through the items, but I'm not quite sure why I cant map through the objects I set in setState(). Note: even if in my setState() I use title: data.title, it doesnt work. Can someone explain where I'm erroring out? Thanks.
in App.js
import React, { Component } from "react";
import { hot } from "react-hot-loader";
import "./App.css";
import ItemsList from './ItemsList';
class App extends Component {
render() {
return (
<div className="App">
<h1> Hello Healthcare </h1>
<ItemsList />
<article className="main"></article>
</div>
);
}
}
export default App;
in NewSingleItem.js
import React, { Component } from "react";
const NewSingleItem = ({item}) => {
<li>
<p>{item.title}</p>
</li>
};
export default NewSingleItem;
The problem is this line:
this.setState({
title: data[i].title,
url: data[i].url,
descrip: data[i].bite,
});
When you state this.state.title to data[i].title, it's no longer an array. You need to ensure it stays an array. You probably don't want to split them up anyway, just keep them all in a self contained array:
this.state = {
// error: null,
// isLoaded: false,
items: [],
};
...
componentDidMount() {
fetch(title_URL)
.then(response => {
return response.json();
})
.then((data) => {
this.setState({
items: data.map(item => ({
title: item.title,
url: item.url,
descrip: item.bite,
})
});
console.log(data[i])
}
})
...
renderItems() {
return this.state.items.map(item => {
<NewSingleItem key={item.title} item={item.title} />;
});
}

Resources