so im trying to pass a parameter from the onPress function into the database.ref().update(parameter here), but the update function cant see the onPress Parameter. here is my code. Can you help me figure out what im doing wrong?
onSubmit(Attribute){
this.setState({
apply:false,
})
const ref = database().ref('Users/Chase/Ivy')
ref.update({Attribute : this.state.inputText}).then(()=> {
console.log('updated!!!');
}).catch((error) => {
console.log(error);
})
}
here is the onPress inline function
{(this.state.apply) ? <Button style={styles.button} onPress={() => this.onSubmit('Class')} title="Apply"/>
You seem to be confused about how objects work in JS.
const fn (param) => {
const obj = {param: "something"};
const obj2 = {[param]: "beta"};
const obj3 = {param};
console.log(obj, obj2, obj3);
};
fn("carlos");
// Outputs:
// {param: "something"}
// {carlos: "beta"}
// {param: "carlos"}
Related
I've got a component that uses the onTouchStart and onTouchEnd and I can't figure out how to test it.
Here's a snack for the code, but the snippet is below:
export default function TouchComponent({
children,
onStart = doNothing,
onEnd = doNothing
}: TouchComponentProps): React.ReactElement {
return (
<View
onTouchStart={(e) => onStart()}
onTouchEnd={(e) => onEnd()}
>{children}</View>
);
}
const doNothing = () => {};
interface TouchComponentProps {
children?: React.ReactNode;
onStart?: () => void;
onEnd?: () => void;
}
Looking at the documentation, there aren't any methods listed for onTouchStart/onTouchEnd, but this method array seems to suggest that it has other methods that can be invoked, but it doesn't look like it works here because fireEvent["onTouchStart"](myComponent); fails with an error saying: TypeError: _reactNative.fireEvent.onTouchStart is not a function.
I've searched around but can't seem to find any documentation or other questions about testing onTouchStart and onTouchEnd, so how do I fire these events?
I figured this out almost immediately after asking this question. In my situation, I can invoke them like this:
import TouchComponent from "../TouchComponent ";
import { render, fireEvent } from "#testing-library/react-native";
it("Invokes onTouchStart and onTouchEnd", () => {
const { getByTestId } = render(
<TouchComponent
onStart={() => {
console.log("onTouchStart invoked");
}}
onEnd={() => {
console.log("onTouchEnd invoked");
}}
testID="my-component" />);
const myComponent = getByTestId("my-component");
// Passing empty {} data, but may need to supply for other use cases.
fireEvent(myComponent, "onTouchStart", {});
fireEvent(myComponent, "onTouchEnd", {};
});
// Console:
// console.log
// onTouchStart invoked
// console.log
// onTouchEnd invoked
I have
function Meal(props) {
const [isFavorite, setIsFavorite] = useState(false);
const setFavorite = () => {
setIsFavorite(currentStatus => !currentStatus);
};
render (etc...)
}
When Calling setFavorite, the isFavorite is not changed. Why?
I have read a lot of questions on StackOverflow around it and I still do not get the logic. I tried using useEffect but without success.
try it like this:
> function Meal(props) {
> const [isFavorite, setIsFavorite] = useState(false);
>
> const handleFavorite = () => {
> setIsFavorite(!isFavorite);
> };
> render (etc...) }
where handleFavorite function triggers the action (if it's called onClick, onChange or something else)
I'm pretty new of RN but I don't really understand Promises with async.
I got how works but I don't use them correctly cause they don't work in my code.
Example
const getAnimationTime = () => {
let res = meditationTime;
return new Promise(resolve => resolve(res));
};
and then:
useEffect(() => {
(async function fetchData() {
const fetcher = await getAnimationTime();
console.log('fetcher', fetcher);
setAnimationTime(fetcher);
})();
console.log('anitime useEffect', animationTime);
}, []);
I did what I saw in tutorials and doesn't work. In this case, I always get undefined
Can someone explain to me how works?
Thanks!
Try to move variable declared inside the Promise block.
const getAnimationTime = () => {
return new Promise((resolve, reject) => {
let res = 100;
resolve(res);
})
};
I solved like adding this:
if (isLoading || animationTime === null) {
return <PulseIndicator color="green" size={50} />;
} else {
return (
<TouchableOpacity
onPress={handlePause}
onLongPress={longPress}
style={styles.container}>
...
It simply waits for the changing state
I don't found a lot of jest&enzyme mock/spy example when react components are functions instead of class...
Since it looks impossible to spy on functionnal components method with "jest.spyOn" like it's possible to do with class components, is there a better or other way than passing method reference in props like my example below ?
it('click on connect button', () => {
let handleConnect = jest.fn();
let shallowLogin = shallow(<Login handleConnect={handleConnect} />);
//const spy = jest.spyOn(shallowLogin.instance(), 'handleConnect');
//Impossible to spyOn like this ?
let button = shallowLogin.find('Styled(Button)');
button.simulate('press');
expect(handleConnect).toHaveBeenCalledTimes(1);
});
I hate to do this because it's intrusive on the component code and it force the change stuff inside for the tests...
Component example :
import useForm from 'react-hook-form';
export default function Login(props) {
const {register, handleSubmit, setValue} = useForm();
const onSubmit = data => {
console.log('data: ', data);
if (FormValidation(data, "login")) {
props.navigation.navigate('App');
}
};
return (
...
<Button style={styles.button} rounded large onPress={handleSubmit(onSubmit)}><Text
style={styles.buttonText}>{locale.t('loginScreen.CONNECT')}</Text></Button>
...
);
}
Currently, I have a page which renders a list of dates, When a user presses a certain date, the user is then taken to a new page which renders the graph of the date that they pressed.
I want to use redux to update props, so that I can render a specific graph based on which button a user has pressed.
Inside my renderList() I return a mapped array that in turn returns a bunch of TouchableOpacities. Inside each TouchableOpacity, inside the onPress event, another function is called that passes all of the information about the test as a parameter. renderList looks like this.
let sorted = _.orderBy(this.props.testResults, testResult => testResult.created, 'desc');
moment.locale(localeToMomentLocale(I18n.locale));
return sorted.map((result, index) => {
let formattedDate = moment(result.created).format(I18n.t('report_header_dformat'));
let correctedDate = vsprintf(I18n.t('report_date_correction'), [formattedDate]);
let analysis = TestAnalysis.run(result);
return (
<TouchableOpacity
onPress={() => this.resultOrTest(result)}
style={styles.row} key={'_' + index}>
</TouchableOpacity>
resultOrTest looks like this:
resultOrTest = (result) => {
console.log('ReportDetailPage: resultOrTest: showing result: ', result.id);
this.props.setResultIdToProps(result.id);
this.props.navigation.navigate('ReportSinglePage');
};
mapDispatchToProps looks like this:
const mapDispatchToProps = (dispatch) => {
return {
setResultIdToProps: () => {
dispatch(setResultIdToProps());
}
}
}
export default connect(mapStateToProps, mapDispatchToProps)(ReportDetailPage);
inside my actions/user.js page.
export const setResultIdToProps = (resultId) => {
// var newId = resultId.toString();
console.log('actions/user.js setResultIdToProps: resultid.......', resultId);
return (dispatch, getState) => {
dispatch({
type: SET_RESULT_ID_TO_PROPS,
resultId
});
}
};
Why does resultId keep coming back as undefined? Did I pass the wrong value/Parameter?
You need to properly pass the parameter to your action dispatcher in mapDispatchToProps. Right now, you're not passing the resultId, hence it is passed as undefined.
const mapDispatchToProps = (dispatch) => {
return {
setResultIdToProps: (resultId) => {
dispatch(setResultIdToProps(resultId));
}
}
}