Skip to content

Commit

Permalink
Make useMediaQuery return the correct value on the first render (#21682)
Browse files Browse the repository at this point in the history
  • Loading branch information
alshakero authored Apr 17, 2020
1 parent 0336a34 commit 886bb15
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
5 changes: 4 additions & 1 deletion packages/compose/src/hooks/use-media-query/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,10 @@ import { useState, useEffect } from '@wordpress/element';
* @return {boolean} return value of the media query.
*/
export default function useMediaQuery( query ) {
const [ match, setMatch ] = useState( false );
const [ match, setMatch ] = useState(
query && window.matchMedia( query ).matches
);

useEffect( () => {
if ( ! query ) {
return;
Expand Down
19 changes: 19 additions & 0 deletions packages/compose/src/hooks/use-media-query/test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,18 @@ describe( 'useMediaQuery', () => {
return `useMediaQuery: ${ queryResult }`;
};

it( 'should return true when query matches on the first render', async () => {
global.matchMedia.mockReturnValue( {
addListener,
removeListener,
matches: true,
} );

const root = create( <TestComponent query="(min-width: 782px)" /> );

expect( root.toJSON() ).toBe( 'useMediaQuery: true' );
} );

it( 'should return true when query matches', async () => {
global.matchMedia.mockReturnValue( {
addListener,
Expand All @@ -55,6 +67,13 @@ describe( 'useMediaQuery', () => {
} );

it( 'should correctly update the value when the query evaluation matches', async () => {
// first render
global.matchMedia.mockReturnValueOnce( {
addListener,
removeListener,
matches: true,
} );
// the query within useEffect
global.matchMedia.mockReturnValueOnce( {
addListener,
removeListener,
Expand Down

0 comments on commit 886bb15

Please sign in to comment.