Skip to content

Instantly share code, notes, and snippets.

@flucivja
flucivja / react_hooks_state_reference_misunderstanding.js
Last active January 17, 2019 07:20
React useState - usage of state reference misunderstanding
// This is the example of React component using useState React Hook which looks alright at first glance but it is not.
// Someone would think that "setText" would set text variable to new text and it can be used immediatelly, but this is not true.
// The setText does not update "text" variable immediatelly, it will update text state somewhere at React internals
// and after the component rerenders the "text" variable will be updated with new value.
// This is not some React magic, this is just how setter works.
// You must remember that functional component is basically the render method of class component
// and if state is changed in render method then component must rerender to access new state.
function Text() {
const [text, setText] = useState('');
@flucivja
flucivja / react_hooks_testing_act_warning.js
Last active February 8, 2019 19:55
React hooks testing act warning
// this is simplified example of testing react hook where I am getting warning that test code should be wrapped in act.
function usePromise(promise) {
const [data, setData] = useState({
isLoading: true,
data: null
});
useEffect(() => {
promise.then((res) => {
// test file
import { given } from 'cypress-bdd';
import { TwitterPage } from './TwitterPage';
describe("Some test suite", () => {
it("some test", () => {
given(TwitterPage, twitterPage => twitterPage.open())
.when(twitterPage =>
twitterPage
.tweetNewMessage("some message")
describe("Some test suite", () => {
it("some test", () => {
cy.open("twitter.com");
cy.get(".new-tweet-btn").click();
cy.get(".input").type("some message");
cy.get(".btn").click();
cy.get(".refresh-btn").click();
cy.get(".tweets").should("contain", "some message")
});
});