Err: Getting an error on implementing react animation.timing method - javascript

For some reason I'm not able to see what I'm doing wrong with my code. I seem to be using Animated just as the documentation shows but this error keeps coming. The code snippet:
import React ,{ Component} from "react";
import { Card } from 'react-native-elements';
import { Text, View ,Animated,Easing} from 'react-native';
import { connect } from 'react-redux';
import { baseUrl } from '../shared/baseUrl';
import { Loading } from './LoadingComponent';
const mapStateToProps = state => {
return {
dishes: state.dishes,
comments: state.comments,
promotions: state.promotions,
leaders: state.leaders
}
}
function RenderItem(props) {
const item = props.item;
if (item != null) {
return(
<Card
featuredTitle={item.name}
featuredSubtitle={item.designation}
image={{uri: baseUrl + item.image}}>
<Text
style={{margin: 10}}>
{item.description}</Text>
</Card>
);
}
}
class Home extends Component{
constructor(props) {
super(props);
this.animatedValue = new Animated.Value(0);
}
componentDidMount () {
this.animate()
}
animate () {
this.animatedValue.setValue(0)
Animated.timing(
this.animatedValue,
{
toValue: 8,
duration: 8000,
easing: Easing.linear
}
).start(() => this.animate())
}
render() {
const xpos1 = this.animatedValue.interpolate({
inputRange:[0,1,3,5,8],
outputRange:[1200 , 600 , 0 , -600 , -1200]
});
return(
<View style = {{flex :1 , flexDirection:'row' , justifyContent : 'center'}}>
<Animated.View style={{width :'100%' , tranform :[{translateX:xpos1}]}}>
<RenderItem item={this.props.dishes.dishes.filter((dish) => dish.featured)[0]}
isLoading={this.props.dishes.isLoading}
erreMess={this.props.dishes.erreMess}
/>
</Animated.View>
</View>
);
}
}
export default connect(mapStateToProps)(Home);
I am trying to implement animation.timing function . As mentioned in documentation I wrote animation.timing function with animatedValue declared in constructor. But when I wrote animate function I got the following error :
I followed documentation of react animation and tried everything on internet to solve the issue but failed .

I think you may just want to loop the animation versus trying to manually "reset" the time, which is recommended against in the documentation.
loop
Loops a given animation continuously, so that each time it reaches the
end, it resets and begins again from the start.
constructor(props) {
super(props);
this.state = {
animatedValue: new Animated.Value(0),
}
}
componentDidMount () {
this.animate();
}
animate = () => {
Animated.loop(
Animated.timing(
this.state.animatedValue,
{
useNativeDriver: true, // loop W/O blocking main JS thread
toValue: 8,
duration: 8000,
easing: Easing.linear
}
),
).start()
}

Related

React Color doesn't let to change the color

I'm using React Color for my project. So I added ChromePicker as in the example into the code.
When the button is clicked, the picker is shown, when it's clicked outside of it - it gets closed. So far so good, it works as expected.
But if I try to change the color, to move the circle or the bars below the gradient there is no action, they are not moving. I don't know why is this happening.
Here is my code:
import React from 'react';
import { Button } from 'semantic-ui-react';
import { ChromePicker } from 'react-color';
export default class Banner extends React.PureComponent {
constructor(props) {
super(props);
this.state = {
displayColorPicker: false,
};
}
handleClick = () => {
this.setState({ displayColorPicker: true });
};
handleClose = () => {
this.setState({ displayColorPicker: false });
};
render() {
const popover = {
position: 'absolute',
zIndex: '2',
};
const cover = {
position: 'fixed',
top: '0px',
right: '0px',
bottom: '0px',
left: '0px',
};
return (
<div>
...//some other code
<div>
<Button onClick={this.handleClick}>Pick Color</Button>
{this.state.displayColorPicker ? (
<div style={popover}>
<div
style={cover}
onClick={this.handleClose}
onKeyDown={this.handleClick}
role="button"
tabIndex="0"
aria-label="Save"
/>
<ChromePicker />
</div>
) : null}
</div>
</div>
);
}
}
This issue might answer your question: https://github.com/casesandberg/react-color/issues/717
Something was changed between version 2.17 and 2.18, you need to either downgrade or make controlled component.
import React from 'react';
import { SketchPicker } from 'react-color';
class Component extends React.Component {
state = {
background: '#fff',
};
handleChangeComplete = (color) => {
this.setState({ background: color.hex });
};
render() {
return (
<SketchPicker
color={ this.state.background }
onChangeComplete={ this.handleChangeComplete }
/>
);
}
}
You should use the onChangeComplete props I suppose, you can find further info here

typeError: (0, _reactRedux.connect) is not a function

I'm unable to display my react native app because of the error.
I have already looked at the other similar post on here, but is did not provide an answer for my question.
below is some code:
import React, {Component} from 'react';
import {View, Text, StyleSheet, Image,TouchableOpacity,Button} from 'react-native';
import TopNavbar from './TopNavbar';
import { connect } from 'react-redux';
import {addIncrement, addDecrement} from '../redux/actions'
class Insigts extends Component {
componentDidMount(){
this.props.addIncrement
}
render(){
const { counter } = this.props
return(
<View style={styles.container}>
a lot of other elements etc...
</View>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
marginTop: 40,
},
somestyle: {
style style style
});
const mapStateToProps = (state) => {
return {
counter: state.counter
}
}
const mapDispatchToProps = (dispatch) => {
return {
addIncrement: () => dispatch(addIncrement()),
addDecrement: () => dispatch(addDecrement()),
}
}
export default connect(
mapStateToProps,
mapDispatchToProps,
)(Insigts)
I have installed all the packages and tried restarting the simulator, but without succes.

Why is setInterval being called automatically in react native

I am trying to make a simple clock that starts and stops on the press of a button. Here I have set a variable equal to a setInterval so that I can clear it later on. But for some reason, it is being called without the button being pressed.
Here the autoInc should have been called ideally when I pressed the "Start" button but it gets called anyway.
import React, { Component } from "react";
import { Text, View, Button } from "react-native";
export default class Counter extends Component {
increaser = () => {
this.setState(prePre => {
return { counter: prePre.counter + 1 };
});
};
constructor(props) {
super(props);
this.state = {
counter: 0,
wantToShow: true
};
autoInc = setInterval(this.increaser, 1000);
}
render() {
if (this.state.wantToShow)
return (
<View>
<Text style={{ color: "red", fontSize: 50, textAlign: "center" }}>
{this.state.counter}
</Text>
<Button title="Start" onPress={this.autoInc} />
</View>
);
}
}
A full react example here, you just have to translate functions in react native.
Create a variable this.interval=null in your constructor, assign to this the interval in the startFn , then just remove it with window.clearInterval(this.interval);
export default class App extends Component {
constructor(props) {
super(props);
this.interval = null;
}
componentDidMount() {}
startFn = () => {
console.log("assign and start the interval");
this.interval = setInterval(this.callbackFn, 1000);
};
stopFn = () => {
console.log("clear interval");
window.clearInterval(this.interval);
};
callbackFn = () => {
console.log("interval callback function");
};
render(props, { results = [] }) {
return (
<div>
<h1>Example</h1>
<button onClick={this.startFn}>start Interval</button>
<button onClick={this.stopFn}>stop Interval</button>
</div>
);
}
}
Codesandbox example here: https://codesandbox.io/s/j737qj23r5
In your constructor, you call setInterval(this.increaser,1000) and then assign its return value to the global property autoInc.
this.autoInc is undefined in your render function.
It looks like
autoInc = setInterval(this.increaser,1000)
is simply incorrectly written and what you want instead is:
this.autoInc = () => setInterval(this.increaser,1000)

Dynamically added view has no style function React Native

I'm using carousel in my app (taken from here https://github.com/nick/react-native-carousel)
I'm trying to add a view each time a user swipe to the right.
That is the code I'm using:
export default class AllRand extends Component
{
constructor(props)
{
super(props);
this.state =
{
myArr: ['Page numebr: ', 'Page numebr: ']
};
}
_onPageSwitchAnimateEnd()
{
this.state.myArr.push('Page numebr: ')
this.setState({
myArr: this.state.myArr
})
}
render()
{
let Arr = this.state.myArr.map((text, index) => {
return <View key={ index } style={ styles.shit1 }><Text>asdasd { index }</Text></View>
})
return (
<Carousel animate={false} hideIndicators={false} onPageChange={() => this._onPressOut()}>
{ Arr }
</Carousel>
);
}
}
I succeed adding a View but it is not with the style, text 'Page number: ' and index...
UPDATE:
changed my code but still doesn't work...
'use strict';
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View
} from 'react-native';
import Carousel from 'react-native-carousel';
import FactsApiFetcher from './facts-api-handler/facts-api-fetcher'
export default class AllRand extends Component
{
constructor(props)
{
const InitialnumberOfPages = 2;
super(props);
this.state =
{
numberOfPages: InitialnumberOfPages,
Pages: this._setInitialPages(InitialnumberOfPages)
};
}
_onPageSwitchAnimateEnd()
{
let updatedNumberOfPages = this.state.numberOfPages + 1;
let newArr = this._addPage(updatedNumberOfPages);
this.setState({
numberOfPages: updatedNumberOfPages,
Pages: newArr
});
}
render()
{
return (
<Carousel animate={false} hideIndicators={false} onPageChange={() => this._onPageSwitchAnimateEnd()}>
{ this.state.Pages }
</Carousel>
);
}
_setInitialPages(numberOfPages)
{
let tempArr = [];
for(let i = 0; i < numberOfPages; i++)
{
tempArr.push(<View key={ i } style={ styles.shit1 }><FactsApiFetcher/></View>);
}
return tempArr;
}
_addPage(updatedNumberOfPages)
{
return this.state.Pages.concat([<View key={ updatedNumberOfPages - 1 } style={ styles.shit1 }><FactsApiFetcher/></View>]);
}
}
const styles = StyleSheet.create({
shit1: {
alignSelf: 'stretch',
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#FFFF00'
}
});
AppRegistry.registerComponent('AllRand', () => AllRand);
So eventually the problem was because there is a bug in the Carousel library I used ( https://github.com/nick/react-native-carousel). From some reason, the callback function that adds the pages is messing up the pages array (don't know why...).]
When I tried using another Carousel library the function worked.
My only advice I can give following this experience is that when you think you tried all the possibilities in order the fix your bug, try changing the libraries you are using (to another same functionality library).

create timer with react native using es6

I am looking to add a timer to my app which is built using react native.
I have looked at the link to the timer mixin in the documentation however I have built the rest of the app using es6 so this won't be compatible.
I have tried the below.
In my Main class I have a function called getTimerCountDown
getTimerCountDown() {
setTimeout(() => {
this.setTimeRemaining(this.getTimeRem()-1);
}, 1000);
}
getTimeRem() {
return this.state.timeRemaining;
}
I have tried calling this in componentDidUpdate as shown below. This works as I want it to if I don't make any other interactions with the UI.
If I do (eg I have a button I can click on the view.) as `componentDidUpdate gets called again the conunter gets really quick (as it is getting called x number of times)
componentDidUpdate(){
this.getTimerCountDown();
}
I am not sure if I am completly on the wrong track here or a small change to what I have done can get me what I want.
What is the best way to get a countdown timer working in react native using es6?
Timer Class
on main page
<Timer timeRem={this.getTimeRem()} />
returns
render(){
return (
<View style={styles.container}>
<Text> This is the Timer : {this.props.setTimer} - {this.props.timeRem} </Text>
</View>
)
}
I'm not really sure how that would work even without any other UI interactions. componentDidUpdate is called every time the component is re-rendered, something that happens when the internal state or passed down props have changed. Not something you can count on to happen exactly every second.
How about moving the getTimerCountDown to your componentDidMount method (which is only called once), and then using setInterval instead of setTimeout to make sure the counter is decremented continuously?
Kinda late, but you can try out this component I made for dealing with timers and es6 components in react-native:
https://github.com/fractaltech/react-native-timer
Idea is simple, maintaining and clearing timer variables on the components is a pain, so simply, maintain them in a separate module. Example:
// not using ES6 modules as babel has broken interop with commonjs for defaults
const timer = require('react-native-timer');
// timers maintained in the Map timer.timeouts
timer.setTimeout(name, fn, interval);
timer.clearTimeout(name);
// timers maintained in the Map timer.intervals
timer.setInterval(name, fn, interval);
timer.clearInterval(name);
// timers maintained in the Map timer.immediates
timer.setImmediate(name, fn);
timer.clearImmediate(name);
// timers maintained in the Map timer.animationFrames
timer.requestAnimationFrame(name, fn);
timer.cancelAnimationFrame(name);
Try this
Timer.js
import React, { Component } from "react";
import { View,Text,Button,StyleSheet } from "react-native";
const timer = () => {};
class Timer extends Component {
constructor(props) {
super(props);
this.state = {
remainingTime: 10
};
}
countdownTimer(){
this.setState({remainingTime:10 });
clearInterval(timer);
timer = setInterval(() =>{
if(!this.state.remainingTime){
clearInterval(timer);
return false;
}
this.setState(prevState =>{
return {remainingTime: prevState.remainingTime - 1}});
},1000);
}
render() {
return (
<View style={styles.container}>
<Text>Remaining time :{this.state.remainingTime}</Text>
<Button title ="Start timer" onPress={()=>this.countdownTimer()}/>
</View>
);
}
}
const styles = StyleSheet.create({
container:{
flex:1,
justifyContent:'center',
alignItems:'center',
}
});
export default Timer;
App.js
import React, { Component } from "react";
import { View,Text,Button,StyleSheet } from "react-native";
import Timer from './timer';
export default class App extends Component{
render(
return (<Timer />)
);
}
Here is full code how you can create a timer (pomodoro Timer) in react-native;
Timer.js
import React from 'react'
import {Vibration, View, Button, Text, TextInput, StyleSheet} from 'react-native'
let pomInterval;
export default class Timer extends React.Component {
constructor() {
super();
this.state = {
minutes: 5,
seconds: 0,
workmins: 5,
worksecs: 0,
breakMins: 2,
breakSecs: 0,
timerState: 'WORK TIMER',
btnState: 'Start'
}
}
vibrate = () => {
Vibration.vibrate([500, 500, 500])
}
pomTimer = () => {
pomInterval = setInterval(() => {
let newSec = this.state.seconds;
newSec--;
if(newSec < 0) {
newSec = 59;
this.state.minutes--;
}
this.setState({
seconds: newSec,
})
if(newSec <= 0 && this.state.minutes <= 0) {
this.vibrate();
if(this.state.timerState == 'WORK TIMER') {
this.setState({
timerState: 'BREAK TIMER',
minutes: this.state.breakMins,
seconds: this.state.breakSecs
})
}else {
this.setState({
timerState: 'WORK TIMER',
minutes: this.state.workmins,
seconds: this.state.worksecs
})
}
}
}, 1000);
}
changeWorkMin = mins => {
clearInterval(pomInterval);
this.setState({
minutes: mins || 0,
workmins: mins || 0,
btnState: 'Start'
})
}
changeWorkSec = secs => {
clearInterval(pomInterval);
this.setState({
seconds: secs || 0,
worksecs: secs || 0,
btnState: 'Start'
})
}
changeBreakMin = mins => {
clearInterval(pomInterval);
this.setState({
breakMins: mins || 0,
btnState: 'Start'
})
}
changeBreakSec = secs => {
clearInterval(pomInterval);
this.setState({
breakSecs: secs || 0,
btnState: 'Start'
})
}
// Creating the functionality for the pause/start button
chnageBtnState = () => {
if(this.state.btnState == 'Start') {
this.pomTimer();
this.setState({
btnState: 'Pause'
})
}else {
clearInterval(pomInterval);
this.setState({
btnState: 'Start'
})
}
}
// Creating the functionality for the reset button
reset = () => {
clearInterval(pomInterval);
if(this.state.timerState == 'WORK TIMER') {
this.setState({
minutes: this.state.workmins,
seconds: this.state.worksecs,
btnState: 'Start'
})
}else {
this.setState({
minutes: this.state.breakMins,
seconds: this.state.breakSecs,
btnState: 'Start'
})
}
}
render() {
return (
<View style={styles.viewStyles}>
<Text style={styles.textStyles}>{this.state.timerState}</Text>
<Text style={styles.textStyles}>{this.state.minutes}:{this.state.seconds}</Text>
<Text>
<Button title={this.state.btnState} onPress={this.chnageBtnState} />
<Button title='Reset' onPress={this.reset} />
</Text>
<Text>Work Time:</Text>
<TextInput style={styles.inputStyles} value={this.state.workmins.toString()} placeholder='Work Minutes' onChangeText={this.changeWorkMin} keyboardType='numeric' />
<TextInput style={styles.inputStyles} value={this.state.worksecs.toString()} placeholder='Work Seconds' onChangeText={this.changeWorkSec} keyboardType='numeric' />
<Text>Break Time:</Text>
<TextInput style={styles.inputStyles} value={this.state.breakMins.toString()} placeholder='Break Minutes' onChangeText={this.changeBreakMin} keyboardType='numeric' />
<TextInput style={styles.inputStyles} value={this.state.breakSecs.toString()} placeholder='Break Seconds' onChangeText={this.changeBreakSec} keyboardType='numeric' />
</View>
)
}
}
// Creating a style sheet to write some styles
const styles = StyleSheet.create({
viewStyles: {
alignItems: 'center'
},
textStyles: {
fontSize: 48
},
inputStyles: {
paddingHorizontal: 50,
borderColor: 'black',
borderWidth: 1
}
})
App.js
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import Timer from './timer';
export default function App() {
return (
<View style={styles.container}>
<Timer />
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
This is how we can create a pomodoro timer, a timer which has both WORK TIMER and BREAK TIMER and it vibrates the phone as one of the timer reaches its end. I also added the input functionality i.e, you can dynamically change the value of the minutes and seconds (whether work timer or break timer is going on). I also added a start/pause button and a reset button.

Categories